如何检查 Google 测试零个或一个函数调用?
How to check with Google Test zero or one function call?
我想编写一个测试,在不同的线程中调用 2 个函数,我希望根据哪个函数首先起作用,会发生这种情况:
EXPECT_CALL(foo, bar(arg_1));
或者这个:
EXPECT_CALL(foo, bar(arg_1)).RetiresOnSaturation();
EXPECT_CALL(foo, bar(arg_2)).RetiresOnSaturation();
EXPECT_CALL(foo, bar(arg_1)).RetiresOnSaturation();
完全按照这个顺序。
最简单的方法是什么?我是 Google 测试的新手。
因为你不能做非此即彼的模式或条件期望,只能选择可选的期望,用 arg1 设置固定期望,用 arg2 设置可选的 (Times(AtMost(1))) 期望,把它们按顺序排列,并让可选期望添加第三个期望。
#include <gtest/gtest.h>
#include <gmock/gmock.h>
class Foo {
public:
MOCK_METHOD1(bar, void(int));
};
class ExpectCall1
{
public:
ExpectCall1(Foo& foo) : foo_(foo) {}
void operator()()
{
EXPECT_CALL(foo_, bar(1)).Times(1);
}
private:
Foo& foo_;
};
class Demo : public ::testing::Test
{
virtual void SetUp()
{
::testing::InSequence dummy;
EXPECT_CALL(foo_, bar(1)).Times(1);
EXPECT_CALL(foo_, bar(2)).Times(::testing::AtMost(1)).
WillOnce(::testing::InvokeWithoutArgs(ExpectCall1(foo_)));
}
protected:
Foo foo_;
};
TEST_F(Demo, Success1)
{
foo_.bar(1);
}
TEST_F(Demo, Success2)
{
foo_.bar(1);
foo_.bar(2);
foo_.bar(1);
}
TEST_F(Demo, Fail1)
{
foo_.bar(1);
foo_.bar(1);
}
TEST_F(Demo, Fail2)
{
foo_.bar(1);
foo_.bar(2);
}
TEST_F(Demo, Fail3)
{
foo_.bar(1);
foo_.bar(1);
foo_.bar(2);
}
我想编写一个测试,在不同的线程中调用 2 个函数,我希望根据哪个函数首先起作用,会发生这种情况:
EXPECT_CALL(foo, bar(arg_1));
或者这个:
EXPECT_CALL(foo, bar(arg_1)).RetiresOnSaturation();
EXPECT_CALL(foo, bar(arg_2)).RetiresOnSaturation();
EXPECT_CALL(foo, bar(arg_1)).RetiresOnSaturation();
完全按照这个顺序。 最简单的方法是什么?我是 Google 测试的新手。
因为你不能做非此即彼的模式或条件期望,只能选择可选的期望,用 arg1 设置固定期望,用 arg2 设置可选的 (Times(AtMost(1))) 期望,把它们按顺序排列,并让可选期望添加第三个期望。
#include <gtest/gtest.h>
#include <gmock/gmock.h>
class Foo {
public:
MOCK_METHOD1(bar, void(int));
};
class ExpectCall1
{
public:
ExpectCall1(Foo& foo) : foo_(foo) {}
void operator()()
{
EXPECT_CALL(foo_, bar(1)).Times(1);
}
private:
Foo& foo_;
};
class Demo : public ::testing::Test
{
virtual void SetUp()
{
::testing::InSequence dummy;
EXPECT_CALL(foo_, bar(1)).Times(1);
EXPECT_CALL(foo_, bar(2)).Times(::testing::AtMost(1)).
WillOnce(::testing::InvokeWithoutArgs(ExpectCall1(foo_)));
}
protected:
Foo foo_;
};
TEST_F(Demo, Success1)
{
foo_.bar(1);
}
TEST_F(Demo, Success2)
{
foo_.bar(1);
foo_.bar(2);
foo_.bar(1);
}
TEST_F(Demo, Fail1)
{
foo_.bar(1);
foo_.bar(1);
}
TEST_F(Demo, Fail2)
{
foo_.bar(1);
foo_.bar(2);
}
TEST_F(Demo, Fail3)
{
foo_.bar(1);
foo_.bar(1);
foo_.bar(2);
}