1

我想做几个 gtest,它们都必须在开始时连接,最后断开连接。两者之间测试的东西各不相同。它们看起来像这样:

TEST_F(..., ...)
{
   // Connect - always the same
   EXPECT_CALL(...);
   ASSERT_TRUE(...);

   // different things happen
   EXPECT_CALL(...);
   EXPECT_CALL(...);
   ASSERT_TRUE(...);


   // Disconnect - always the same
   EXPECT_CALL(...);
   ASSERT_TRUE(...);
}

因此,我想要这样的东西:

void connect()
{
   EXPECT_CALL(...);
   ASSERT_TRUE(...);
}

void disconnect()
{
   EXPECT_CALL(...);
   ASSERT_TRUE(...);
}

TEST_F(..., ...)
{
   connect();

   // different things happen
   EXPECT_CALL(...);
   EXPECT_CALL(...);
   ASSERT_TRUE(...);

   disconnect();
}

这可能吗?有没有更聪明的方法来解决这个问题?

4

2 回答 2

2

另一个答案提供了通常如何完成的示例 - 您可能会放入connect()测试夹具构造函数和disconnect()测试夹具析构函数。您可能需要阅读这部分文档以了解更多信息。

回答“这可能吗?”这个问题。带有一些文档(来自Advanced googletest Topics):

您可以在任何 C++ 函数中使用断言。特别是,它不必是测试夹具类的方法。一个限制是产生致命故障的断言 ( FAIL*and ASSERT_*) 只能用于void-returning 函数。

于 2021-01-05T16:30:46.773 回答
0

这是在测试夹具中设置模拟对象的完整示例,每个对象实例化一次TEST_F

#include <gmock/gmock.h>
#include <gtest/gtest.h>

class Object {
public:
  void someMethod();
};

class MockObject : public Object {
public:
  MOCK_METHOD(void, someMethod, (), ());
};

class TestFixture : public testing::Test {

public:
  MockObject object;

  TestFixture() {
    std::cout << "Creating fixture." << std::endl;
    EXPECT_CALL(object, someMethod()).Times(1);
  }

  ~TestFixture() { std::cout << "Destroying fixture." << std::endl; }
};

TEST_F(TestFixture, SomeTest1) {
  std::cout << "Performing test 1." << std::endl;
  object.someMethod();
}

TEST_F(TestFixture, SomeTest2) {
  std::cout << "Performing test 2." << std::endl;
  object.someMethod();
}

该示例可以编译为:

g++ $(pkg-config --cflags --libs gtest gtest_main gmock) test.cpp

输出将如下所示:

$ ./a.out 
Running main() from /build/gtest/src/googletest-release-1.10.0/googletest/src/gtest_main.cc
[==========] Running 2 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 2 tests from TestFixture
[ RUN      ] TestFixture.SomeTest1
Creating fixture.
Performing test 1.
Destroying fixture.
[       OK ] TestFixture.SomeTest1 (0 ms)
[ RUN      ] TestFixture.SomeTest2
Creating fixture.
Performing test 2.
Destroying fixture.
[       OK ] TestFixture.SomeTest2 (0 ms)
[----------] 2 tests from TestFixture (0 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 1 test suite ran. (0 ms total)
[  PASSED  ] 2 tests.
于 2021-01-05T12:46:00.780 回答