Reputation: 31
I want to make several gtests which all have to have a connect in the beginning, and a disconnect in the end. The things that are tested in between vary. They look as such:
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(...);
}
Hence, I would like to have something like this:
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();
}
Is this possible? Are there smarter ways to solve this problem?
Upvotes: 2
Views: 891
Reputation: 22354
The other answer provides example how it's usually done - you'd likely put connect()
in test fixture constructor and disconnect()
in test fixture destructor. You may want to read this section of documentation to learn more.
To answer the question "Is this possible?" with some documentation (from Advanced googletest Topics):
You can use assertions in any C++ function. In particular, it doesn't have to be a method of the test fixture class. The one constraint is that assertions that generate a fatal failure (
FAIL*
andASSERT_*
) can only be used invoid
-returning functions.
Upvotes: 2
Reputation: 4620
Here is a full example for setting up the mock object in the test fixture, which is instantiated once for each 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();
}
The example can be compiled with:
g++ $(pkg-config --cflags --libs gtest gtest_main gmock) test.cpp
The output would look like this:
$ ./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.
Upvotes: 0