如何使用谷歌测试零或一个函数调用进行检查

How to check with Google Test zero or one function call?

本文关键字:一个 函数调用 进行检查 谷歌 何使用 测试      更新时间:2023-10-16

我想写一个测试,在不同的线程中调用两个函数,我希望根据哪个函数首先工作,会出现以下情况:

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();

正是按照这个顺序。最简单的方法是什么?我是谷歌测试的新手。

由于您不能执行模式或条件期望中的任何一个,请仅使用可选期望,将固定期望设置为arg1,将可选(次数(AtMost(1)))期望设置为arg2,按顺序排列,并使可选期望加上第三个期望。

#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);
}
相关文章: