测试如何验证特定函数是否已执行

时间:2016-09-01 07:04:08

标签: c++ googletest

我需要验证(重)函数是否仅在正确的输入上执行。有没有简单的方法来做到这一点?

目前我看到了两种前进方式

  1. 使用仅在测试中使用的额外参数修改函数

  2. 将函数包装在可以跟踪执行的内容中并使用它来替换函数

  3. 1相当难看,我不知道怎么做2

    示例:

    例如,我想测试一个< = 3

    时不执行此处的重量
    void function_to_test(int a){
      if(a>3){
        heavy();
      }
    }
    

1 个答案:

答案 0 :(得分:0)

以下是如何使用gtest编写单元测试的示例。

class Turtle {
virtual ~Turtle() {}
virtual void PenUp() = 0;
virtual void PenDown() = 0;
virtual void Forward(int distance) = 0;
virtual void Turn(int degrees) = 0;
virtual void GoTo(int x, int y) = 0;
virtual int GetX() const = 0;
virtual int GetY() const = 0;
};

#include "gmock/gmock.h"  // Brings in Google Mock.
class MockTurtle : public Turtle {
 public:
  ...
  MOCK_METHOD0(PenUp, void());
  MOCK_METHOD0(PenDown, void());
  MOCK_METHOD1(Forward, void(int distance));
  MOCK_METHOD1(Turn, void(int degrees));
  MOCK_METHOD2(GoTo, void(int x, int y));
  MOCK_CONST_METHOD0(GetX, int());
  MOCK_CONST_METHOD0(GetY, int());
};

#include "path/to/mock-turtle.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using ::testing::AtLeast;                     // #1

TEST(PainterTest, CanDrawSomething) {
  MockTurtle turtle;                          // #2
  EXPECT_CALL(turtle, PenDown())              // #3
      .Times(AtLeast(1));

  Painter painter(&turtle);                   // #4

  EXPECT_TRUE(painter.DrawCircle(0, 0, 10));
}                                             // #5

int main(int argc, char** argv) {
  // The following line must be executed to initialize Google Mock
  // (and Google Test) before running the tests.
  ::testing::InitGoogleMock(&argc, argv);
  return RUN_ALL_TESTS();
}

更多文档位于以下链接

https://github.com/google/googletest/blob/master/googlemock/docs/ForDummies.md