C++ googlemock EXPECT_呼叫,行为变化较小

C++ googlemock EXPECT_呼叫,行为变化较小,c++,googletest,googlemock,C++,Googletest,Googlemock,在googlemock和googletest的帮助下,我建立了一个测试,检查不同的模拟错误是否被测试方法正确处理。基本上,我的代码如下所示: // setup mock object, and object under test // setup initial EXPECT_CALL expectations // this expected method call in the middle mocks a failure EXPECT_CALL(*mock, meth

在googlemock和googletest的帮助下,我建立了一个测试,检查不同的模拟错误是否被测试方法正确处理。基本上,我的代码如下所示:

  // setup mock object, and object under test

  // setup initial EXPECT_CALL expectations

  // this expected method call in the middle mocks a failure 
  EXPECT_CALL(*mock, method(arg_in)).
    Times(1).
    WillOnce(Throw(exception_of_type_A));

  // setup cleanup EXPECT_CALL expectations

  // Now invoke method in object under test.
  // Expect exception has been translated to different type.
  EXPECT_THROW(x.method_under_test(), exception_type_B);

  // destructor of mock object will check the mock method invocations
现在,这里失败的模拟方法不仅可以通过抛出类型A的异常而失败,还可以通过抛出类型B的异常或返回意外的返回值而失败

我可以通过复制和粘贴完整的TEST()并更改行为不端的mocked method1的功能来轻松实现这一点。但这会使代码变得混乱。即使我记录了这3个测试完全相同,除了WillOnce()操作规范中mocked method1如何失败之外,如果这仍然是真的,人类读者仍然需要仔细比较

在googletest/googlemock中,在三个测试之间共享公共代码并使它们在WillOnce()操作中有所不同的正确方法是什么

我想到的是:宏、带有WillOnce()操作的容器上的循环、googletest装置、用于设置和清理的静态助手方法


我还不熟悉googletest,不知道如何解决这个问题。

现在,我在一个接受动作作为参数的模板化静态函数中实现测试逻辑:

template <typename A>
static void paramererizeable_test(A failingAction) {
  // set everything up
  EXPECT_CALL(*mock, method(arg_in)).
    Times(1).
    WillOnce(failingAction);
  // set up more expectations
  // trigger the calls
}

TEST(Section, Method) {
  paramererizeable_test(Throw(exception_of_type_A));
  paramererizeable_test(Throw(exception_of_type_B));
  paramererizeable_test(Return(unexpected_return_value));
}
模板
静态空隙参数可调_试验(失败动作){
//安排一切
EXPECT_调用(*mock,method(arg_in))。
次(1)。
WillOnce(失败行动);
//建立更多的期望
//触发呼叫
}
试验(章节、方法){
可参数化_测试(抛出(_类型_A的异常_));
可参数化_测试(抛出(_类型_B的异常_));
可参数化_测试(返回值(意外_返回值));
}
不确定这是应该怎么做,或者是否有更好的方法,但它是有效的,并且可读