【发布时间】:2018-08-14 06:36:20
【问题描述】:
我目前正在尝试在 C++ 中测试 google test 的功能。 (更具体地说:google mock)
现在我遇到了一个问题。它应该超级简单,它以前工作过,但不知何故它搞砸了,框架没有按预期工作。废话不多说,这是我的问题。
我尝试做一个简单的事情来查看函数“DoSomeMathTurtle”是否被调用一次并返回预期值。但是“.WillOnce(Return(x))”操纵了它始终为真的期望值。
class Turtle {
...
virtual int DoSomeMathTurtle(int , int); //Adds two ints together and returns them
...
};
我的模拟课:
class MockTurtle : public Turtle{
public:
MockTurtle(){
ON_CALL(*this, DoSomeMathTurtle(_, _))
.WillByDefault(Invoke(&real_, Turtle::DoSomeMathTurtle));
//I did this so the function gets redirected to a real
// object so those two numbers actually get added together
//(without that it returns always 0)
}
MOCK_METHOD2(DoSomeMathTurtle, int(int, int));
private:
Turtle real_;
};
基础测试类:
class TestTurtle : public ::testing::Test{
protected:
//De- & Constructor
TestTurtle(){}
virtual ~TestTurtle(){} //Has to be virtual or all tests will fail
//Code executed before and after every test
virtual void SetUp(){}
virtual void TearDown(){}
//Test Fixtures which can be used in each test
MockTurtle m_turtle;
};
我的测试用例:
TEST_F(TestTurtle, MathTest){
int x = 2; // Expected value
int rvalue; // Returned value of the function
EXPECT_CALL(m_turtle, DoSomeMathTurtle(_, _))
.Times(1)
.WillOnce(Return(x));
rvalue = m_turtle.DoSomeMathTurtle(3,3); // rvalue should be 6 but it is 2
cout << "[ ] Expected value: " << x << " Returned value " << rvalue << endl;
//This prints: [ ] Expected value 2 Returned value 2
//Then the test passes !?
}
}
当我将"WillOnce(Return(x))" 注释掉时,右值变为 6(它应该变为的值)。当"WillOnce(Return(x))" &
ON_CALL(*this, DoSomeMathTurtle(_, _))
.WillByDefault(Invoke(&real_, Turtle::DoSomeMathTurtle));
(在我的模拟类的构造函数中)被注释掉,右值变为 0(这也应该发生)。
所以只要"WillOnce(Return(x))" 在游戏中,右值总是"x"。
提前感谢您的帮助! 祝您度过愉快、没有错误的一天!
【问题讨论】:
-
这是模拟所需的行为。您可以想象您有一些从磁盘获取数据的类。您通常避免在单元测试中使用磁盘。所以你嘲笑你的班级并告诉它你期望它返回给你什么。这完全没问题,这里没有错误。
-
哇,答案很快,谢谢!
-
所以如果理解正确:为了节省磁盘空间,我告诉 gmock“函数将返回什么”而不是“设置必须匹配的比较器”以使测试通过?
标签: c++ unit-testing return-value googletest googlemock