问题描述
我想做几个 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();
}
这可能吗?有没有更聪明的方法来解决这个问题?
解决方法
另一个答案提供了通常如何完成的示例 - 您可能将 connect()
放在测试夹具构造函数中,将 disconnect()
放在测试夹具析构函数中。您可能需要阅读 this section of documentation 以了解更多信息。
回答问题“这可能吗?”一些文档(来自Advanced googletest Topics):
您可以在任何 C++ 函数中使用断言。特别是,它不必是测试装置类的方法。一个限制是产生致命失败的断言(FAIL*
和 ASSERT_*
)只能在返回 void
的函数中使用。
以下是在测试装置中设置模拟对象的完整示例,它为每个 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.