Google 测试 WillOnce(Return( )) 操纵预期的 return 值

Google Test WillOnce(Return( )) manipulates the expected return-value

我目前正在尝试用 C++ 测试 google 测试的功能。 (更具体地说:google mock)

现在我运行遇到了问题。它应该非常简单,它以前工作过,但不知何故搞砸了,框架没有按预期工作。废话少说,我的问题来了。

我尝试做一些简单的事情来查看函数 "DoSomeMathTurtle" 是否被调用一次并且 returns 是否为预期值。但是“.WillOnce(Return(x))”操纵的期望值始终为真。

class Turtle {
    ...
    virtual int DoSomeMathTurtle(int , int); //Adds two ints together and returns them
    ...
};

我的嘲笑class:

    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:

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)); 

(在我的 mock-class 的构造函数中)被注释掉,右值变为 0(这也应该发生)。

所以只要 "WillOnce(Return(x))" 在游戏中,右值总是 "x"

在此先感谢您的帮助! 祝您度过美好的一天!

模拟就是期望。当您在测试中写入时:

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

您预计 m_turtle 会调用一次 DoSomeMathTurtle 接受任何参数,并且会调用一次 return x.

因为x等于2,那么当你下次使用m_turtle.DoSomeMathTurtle(any_argument, any_argument);的时候 它将 return 2.

如果你想检查参数,你应该在 googlemock 中寻找匹配器,f.e 当你

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

当第一个等于 3 而第二个小于 3 时,您会期望 DoSomeMathTurtle 将采用两个参数。

如果你想在考试中取得好成绩,你可以这样写:

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