Google Test WillOnce(Return())处理预期的返回值

时间:2018-08-14 06:36:20

标签: c++ unit-testing return-value googletest googlemock

我目前正在尝试在c ++中测试google test的功能。 (更具体而言:Google模拟)

现在我遇到了一个问题。它应该超级简单,以前就可以使用,但是以某种方式搞砸了,并且该框架无法按预期工作。聊够了,这是我的问题。

我尝试做一件简单的事情,看看函数“ 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))"时,rvalue变成6(它应该变成的值)。当"WillOnce(Return(x))"

ON_CALL(*this, DoSomeMathTurtle(_, _))
                .WillByDefault(Invoke(&real_, Turtle::DoSomeMathTurtle)); 

(在我的模拟类的构造函数中)被注释掉,rvalue变为0(这也应该发生)。

一旦"WillOnce(Return(x))"出现在游戏中,右值便始终为"x"

预先感谢您的帮助! 祝您有美好的一天,没有错误!

1 个答案:

答案 0 :(得分:1)

模拟就是关于期望。当您编写测试时:

EXPECT_CALL(m_turtle, DoSomeMathTurtle(_, _))
  .Times(1)
  .WillOnce(Return(x));

您期望m_turtle将一次调用DoSomeMathTurtle,它将接受任何参数,而一次调用return x

因为x等于2,所以下次使用m_turtle.DoSomeMathTurtle(any_argument, any_argument);时 它将返回2。

如果要检查参数,则应在googlemock中查找匹配项,例如在创建时

EXPECT_CALL(m_turtle, DoSomeMathTurtle(Eq(3), Lt(3)))

您会期望DoSomeMathTurtle在第一个等于3而第二个小于3时会接受两个参数。

如果您想在测试中获得良好的结果,您可以编写:

EXPECT_CALL(m_turtle, DoSomeMathTurtle(Eq(3), Eq(3)))
  .Times(1)
  .WillOnce(Return(6));
  rvalue = m_turtle.DoSomeMathTurtle(3,3); // rvalue is equal to 6