Bul*_*net 17 c++ unit-testing gmock
鉴于:
#include "gmock/gmock.h"
#include <string>
using namespace testing; // tsk, tsk
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
struct Mockable {
virtual std::string ify(int x) const;
};
std::string Mockable::ify(int x) const
{
return std::to_string(x);
}
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
struct Mocked : public Mockable {
MOCK_CONST_METHOD1(ify, std::string(int));
};
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
std::string tested(Mockable const& u, int x)
{
return u.ify(x);
}
TEST(TC,T42)
{
Mocked mock;
ON_CALL(mock, ify(Eq(42)))
.WillByDefault(Return("33"));
std::string const& ret = tested(mock, 42);
EXPECT_EQ("42", ret);
}
TEST(TC,T33)
{
Mocked mock;
ON_CALL(mock, ify(Eq(33)))
.WillByDefault(Return("333"));
std::string const& ret = tested(mock, 42);
EXPECT_EQ("42", ret);
}
int main(int argc, char *argv[])
{
::testing::InitGoogleTest(&argc, argv);
//::testing::FLAGS_gmock_verbose = "info";
return RUN_ALL_TESTS();
}
Run Code Online (Sandbox Code Playgroud)
输出是:
$ ./mocktest
[==========] Running 2 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 2 tests from TC
[ RUN ] TC.T42
GMOCK WARNING:
Uninteresting mock function call - taking default action specified at:
mocktest.cc:40:
Function call: ify(42)
Returns: "33"
Stack trace:
mocktest.cc:44: Failure
Value of: ret
Actual: "33"
Expected: "42"
[ FAILED ] TC.T42 (0 ms)
[ RUN ] TC.T33
GMOCK WARNING:
Uninteresting mock function call - returning default value.
Function call: ify(42)
Returns: ""
Stack trace:
mocktest.cc:54: Failure
Value of: ret
Actual: ""
Expected: "42"
[ FAILED ] TC.T33 (1 ms)
[----------] 2 tests from TC (1 ms total)
[----------] Global test environment tear-down
[==========] 2 tests from 1 test case ran. (1 ms total)
[ PASSED ] 0 tests.
[ FAILED ] 2 tests, listed below:
[ FAILED ] TC.T42
[ FAILED ] TC.T33
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,Gmock在应用行为时表现正确(或不在TC33中).但为什么在两种情况下都会说"无趣的模拟函数调用"呢?模拟函数调用仅在指定时才有意义EXPECT_CALL吗?
πάν*_*ῥεῖ 21
"只有在使用EXPECT_CALL指定时,模拟函数调用才有意义吗?"
简而言之,是的.
该ON_CALL()宏只影响将要采取的一个模拟的方法调用的动作,而不是调用预期的模拟对象上设置.
您可以使用NiceMock<>模板来抑制这些警告.
引用谷歌嘲笑"Cookbook"
假设您的测试使用模拟类MockFoo:
TEST(...) {
MockFoo mock_foo;
EXPECT_CALL(mock_foo, DoThis());
... code that uses mock_foo ...
}
Run Code Online (Sandbox Code Playgroud)
如果调用除DoThis()之外的mock_foo方法,Google Mock会将其报告为警告.但是,如果您重写测试以改为使用NiceMock,则警告将消失,从而产生更清晰的测试输出:
using ::testing::NiceMock;
TEST(...) {
NiceMock<MockFoo> mock_foo;
EXPECT_CALL(mock_foo, DoThis());
... code that uses mock_foo ...
}
Run Code Online (Sandbox Code Playgroud)
NiceMock<MockFoo>是它的子类MockFoo,因此它可以在任何MockFoo被接受的地方使用.
| 归档时间: |
|
| 查看次数: |
13642 次 |
| 最近记录: |