假设我有一个简单的模拟测试。
#include "boost/interprocess/detail/interprocess_tester.hpp"
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using namespace ::testing;
struct IInterface
{
virtual void method(int foo) = 0;
};
struct SimpleMock : public IInterface
{
MOCK_METHOD1(method, void(int foo));
};
struct TestFixture : public Test
{
TestFixture()
{
// Don't care about other invocations not expected
EXPECT_CALL(mock, method(_)).Times(AnyNumber());
}
void setupExpectation(int data)
{
EXPECT_CALL(mock, method(data)).Times(1);
}
SimpleMock mock;
};
TEST_F(TestFixture, SimpleTest)
{
setupExpectation(2);
mock.method(2);
setupExpectation(5);
mock.method(3); // will fail expectation
}
这将失败,并显示下面的消息引用辅助方法,这使得调试或确定哪个期望失败变得困难,因为我没有看到我调用的行
setupExpectation
或实际的参数值。
test_HarmonicTherapyStateMachineAit.cpp:27: Failure
Actual function call count doesn't match EXPECT_CALL(mock, method(data))...
Expected: to be called once
Actual: never called - unsatisfied and active
请注意,我的实际用例有更复杂的期望调用,我认为有必要将其拆分为一个单独的方法(并在一个测试中具有多个期望)。但是,我不确定如何从中获取更多信息性错误消息。
我读过http://google.github.io/googletest/gmock_cook_book.html#controlling-how-much-information-gmock-prints。然而,这提供了比我真正想要的更多的信息,这只是调用
setupExpectation
的函数的行号。
我也只是尝试制作一个宏来包装共同的期望。在这个简单的例子中这很容易。然而,我的实际用例有更复杂的逻辑,我不想将其放入宏中。
即使我可以做类似
EXPECT_CALL(...).Times(1) << "argument: " << foo;
的事情,那也会有帮助的。
如有任何帮助,我们将不胜感激。
目前我遇到了同样的问题,gmock 为我提供的信息很少。我的解决方案是编写一个自定义匹配器。
EXPECT_CALL 宏的语法根据文档:
EXPECT_CALL(mock_object, method(matchers))
一个快速的解决方案可能是编写一个 matcher,如果出现错误,它会在屏幕上打印一条消息。
例如:
MATCHER_P2(isEqual, expected, line, "")
{
bool isEqual = arg == expected;
if(!isEqual)
printf("Expected argument: %d, actual: %d (EXPECT_CALL line: %d)\n", expected, arg, line);
return isEqual;
}
EXPECT_CALL 然后更改为
EXPECT_CALL(mock, method(isEqual(3, __LINE__))).Times(1);
如果您有其他/更好的解决方案,请告诉我。