Constructor for a test class in Google Test - c++

namespace {
using namespace std;
// Declare the google test case
class InjectorTest : public ::testing::Test {
std::shared_ptr<MyData>> m_reader;
public:
static void SetUpTestCase() {
}
static void TearDownTestCase() {
}
InjectorTest()
{
//Create Reader code here !!!!
m_reader = CreateReader();
}
std::shared_ptr<DDSTopicReader<MyData>> getXMLReader() {
return m_reader;
}
};
TEST_F(InjectorTest, CreateReaderAndGetTopic) {
auto reader = getXMLReader();
std::string topic_name = reader->getTopicName();
EXPECT_EQ(topic_name, "test_topic");
}
}; // anonymous namespace
My questions is
1) When I run the test case CreateReaderAndGetTopic does the Constructor of InjectorTest gets called before executing the test case? Or should it be called explictly ?
2) Should my class InjectorTest have a constructor or should the code inside the constructor be moved to SetUpTestCase.

Let's mention first that the static class members SetUpTestCase and
TearDownTestCase have been renamed respectively to SetUpTestSuite and TearDownTestSuite
since googletest v1.8. See Beware of the nomenclature
They did that because the names SetUpTestCase and TearDownTestCase were grossly
misleading. They suggest functions that will be run in every case of a test that
is derived from the fixture class in which they are defined, which they weren't.
SetUpTestCase was in fact run before the first of all tests derived from the fixture
(and still is, if you have an older googletest installation), and TearDownTestCase
was run after the last of all tests derived from the fixture.
As of googletest 1.8, all of the tests that derived from a fixture - which we'd
naturally call its test cases - are collectively regarded as a test suite;
so the set-up function that runs before all of them is now called SetUpTestSuite
and the tear-down function that runs after of them is called TearDownTestSuite.
I will stick with the new improved names as I have the latest rev of googletest.
Look at this gtest code that demonstrates the calling order of a fixture's
constructor and destructor, SetUp and TearDown, SetUpTestSuite and TearDownTestSuite:
gtester.cpp
#include <gtest/gtest.h>
#include <iostream>
struct fixture : ::testing::Test
{
fixture() {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
~fixture() override {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
void SetUp() override {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
void TearDown() override {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
static void SetUpTestSuite() {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
static void TearDownTestSuite() {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
TEST_F(fixture, One) {
ASSERT_EQ(1,1);
}
TEST_F(fixture, Two) {
ASSERT_NE(1,0);
}
TEST_F(fixture, Three) {
ASSERT_LT(1,2);
}
You can get a useful peek under the hood if you just preprocess this
file (and preferably, pipe through a pretty-printer) and look at what comes out:
$ g++ -E -P gtester.cpp | clang-format > gtester.ii
In gtester.ii you'll be able to find:
...
class fixture_One_Test : public fixture {
public:
fixture_One_Test() {}
private:
virtual void TestBody();
static ::testing::TestInfo *const test_info_ __attribute__((unused));
fixture_One_Test(fixture_One_Test const &) = delete;
void operator=(fixture_One_Test const &) = delete;
};
::testing::TestInfo *const fixture_One_Test::test_info_ =
::testing::internal::MakeAndRegisterTestInfo(
"fixture", "One", nullptr, nullptr,
::testing::internal::CodeLocation("gtester.cpp", 31),
(::testing::internal::GetTypeId<fixture>()),
::testing::internal::SuiteApiResolver<fixture>::GetSetUpCaseOrSuite(),
::testing::internal::SuiteApiResolver<
fixture>::GetTearDownCaseOrSuite(),
new ::testing::internal::TestFactoryImpl<fixture_One_Test>);
void fixture_One_Test::TestBody() {
switch (0)
case 0:
default:
if (const ::testing::AssertionResult gtest_ar =
(::testing::internal::EqHelper<
decltype(::testing::internal::IsNullLiteralHelper(
1, ::testing::internal::TypeIsValidNullptrConstant<decltype(
1)>()))::value>::Compare("1", "1", 1, 1)))
;
else
return ::testing::internal::AssertHelper(
::testing::TestPartResult::kFatalFailure, "gtester.cpp", 32,
gtest_ar.failure_message()) = ::testing::Message();
}
...
That is what the test case:
TEST_F(fixture, One) {
ASSERT_EQ(1,1);
}
expands to after preprocessing. When googletest runs test case fixture.One:
It constructs a new instance of fixture_One_Test - which by inheritance, is
a new instance of fixture.
The base fixture constructor is called.
The derived fixture_One_Test constructor is called. (But it's empty.)
Googletest calls fixture::Setup() through the fixture_One_Test instance.
It calls fixture_One_Test::TestBody() through the fixture_One_Test instance,
which executes the payload of the test case.
It calls calls fixture::TearDown() through the fixture_One_Test instance.
It destroys the fixture_One_Test instance, which -
Calls the fixture_One_Test destructor, which simply -
Calls the fixture destructor.
Similarly for fixture_Two_Test and fixture_Three_Test.
And just before all of that, googletest calls fixture::SetupTestSuite, if it's
is defined.
And just after all of that, googletest calls fixture::TearDownTestSuite, if it's
is defined.
Now let's see that in action:
$ g++ -Wall -Wextra -o gtester gtester.cpp -lgtest_main -lgtest -pthread
$ ./gtester
Running main() from /home/imk/Downloads/googletest-master/googletest/src/gtest_main.cc
[==========] Running 3 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 3 tests from fixture
static void fixture::SetUpTestSuite()
[ RUN ] fixture.One
fixture::fixture()
virtual void fixture::SetUp()
virtual void fixture::TearDown()
virtual fixture::~fixture()
[ OK ] fixture.One (0 ms)
[ RUN ] fixture.Two
fixture::fixture()
virtual void fixture::SetUp()
virtual void fixture::TearDown()
virtual fixture::~fixture()
[ OK ] fixture.Two (0 ms)
[ RUN ] fixture.Three
fixture::fixture()
virtual void fixture::SetUp()
virtual void fixture::TearDown()
virtual fixture::~fixture()
[ OK ] fixture.Three (0 ms)
static void fixture::TearDownTestSuite()
[----------] 3 tests from fixture (0 ms total)
[----------] Global test environment tear-down
[==========] 3 tests from 1 test case ran. (0 ms total)
[ PASSED ] 3 tests.
SetUpTestSuite() and TearDownTestSuite() each run just once. The constructor,
destructor, SetUp() and TearDown() each run 3 times = the number of test cases
in the test suite.
So to your two questions:
When I run the test case CreateReaderAndGetTopic does the Constructor of InjectorTest gets called before executing the test case? Or should it be called explictly ?
The InjectorTest constructor is necessarily called to construct an instance of the class CreateReaderAndGetTopic_InjectorTest_Test,
which Googletest does for you. It is called before SetUp(), which is called before TestBody(), which is the payload of the test case.
Should my class InjectorTest have a constructor...
InjectorTest will have a constructor, either by default or as defined by you; so you're
wondering whether you should define one.
You should define one if you have something to do that needs to be done anew in preparation
for each test case, and that had better be done before the SetUp() for each test case.
... or should the code inside the constructor be moved to SetUpTestCase?
The code you have inside the constructor:
m_reader = CreateReader();
should be moved out to SetUpTestCase - a.k.a SetUpTestSuite - if it is something
that does not need to be done anew in preparation for each test case but needs to be
done once just before all test cases of InjectorTest.
As it stands, you cannot move that constructor code into SetUpTestSuite because it initializes a non-static
class member of InjectorTest, m_reader. But do you in fact need or want a new XMLReader
to be created by CreateReader() for each test case? Only you can decide.
If you do want to create a new reader for each test case, then you face the choice
of creating it in the constructor or in SetUp(). Here you can be guided by the
Googletest FAQ Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()?

If you want to make sure your test cases in a fixture have the same setup, you should implement the SetUp and TearDown methods (notice the case)
Your InjectorTest fixture only gets constructed once, but the SetUp step (resp. the TearDown step) will be run before (resp. after) your test case is executed.
The constructor should only deal with things that should be only done once (if any), any behavior you want to enforce for your test cases should go in these 2 methods. In your example, if the m_reader member can be shared across all your test cases, you can initialize it in the constructor like you did.
To sumup, here is the sequence of operations that will be run:
InjectorTest::InjectorTest(): test fixture is constructed
For each test case:
InjectorTest::SetUp(): setup for test case
Test case is run (in your example InjectorTest::CreateReaderAndGetTopic)
InjectorTest::TearDown(): setup is undone for next case
InjectorTest::~InjectorTest(): destruction of the fixture object

Related

What is the use of a test fixture in google test?

Google recommends to use the text fixture constructor/destructor when possible instead of SetUp()/TearDown() (https://google.github.io/googletest/faq.html#CtorVsSetUp). Assuming I do it this way, what is the use of even using a test fixture? How are the following different, and what is the advantage of the first?
TEST_F(MyFixture, MyTest) {
... run test, using member functions of MyFixture for common code ...
}
TEST(MySuite, MyTest) {
MyFixture fixture; // will call ctor
... run test, using public functions of MyFixture for common code ...
} // will call dtor
The advantages are visible when there are more than one TEST/TEST_F.
Compare:
TEST(MyTest, shallX)
{
MyTest test;
test.setUpX();
test.objectUnderTest.doX();
}
TEST(MyTest, shallY)
{
OtherTest test;
test.setUpY();
test.objectUnderTest.doY();
}
with
TEST_F(MyTest, shallX)
{
setUpX();
objectUnderTest.doX();
}
TEST_F(MyTest, shallY)
{
setUpY();
objectUnderTest.doY();
}
What we can see, are:
DRY (don't repeat yourselves) principle is followed. You do not have to repeat creating of some test-helper object. In TEST_F - the macro creates this instance.
The code is safer with TEST_F. See MyTest..shallDoY -- have you spot that wrong test-helper object is used, not the one that testname is promising.
So it is better to use TEST_F if your tests require some test-helper class.
If not - then use TEST.

Calling one TEST_F in another TEST_F in gtest

I have a test suite in gtest.My Test Fixture class has two tests,one is Test_F(functional),Test_F(performance).
I have the implementation in such a way that Test_F(performance) is dependent on the run of Test_F(functional).
I want to handle the case,where when Test_F(functional) is disabled.So,my approach is calling Test_F(functional) from inside Test_F(performance).
I am not sure,how this is done in gtest,calling a test_function,inside another test_function.
Any help is appreciated.
AFAIK there's no option to call test function inside another test function. However, to share the code between test cases, you can define a helper method in the test suite:
class FooBarTestSuite : public ::testing::Test {
public:
TestSuite() {
// init code goes here
// foo and bar are accessible here
}
~TestSuite() {
// deinit code goes here
// foo and bar are accessible here
}
void CommonCode() {
// common test case code here
// foo and bar are accessible here
}
ClassFoo foo{};
ClassBar bar{};
};
TEST_F(FooBarTestSuite, PerformanceTest) {
CommonCode();
// performance-specific code here
}
TEST_F(FooBarTestSuite, FunctionalTest) {
CommonCode();
// functional-specific code here
}
In order to run a specific test case, use --gtest_filter=*Performace* or --gtest_filter=*Functional* as the parameter.

GoogleTest Test Fixture Clarification

When I write Test fixture to test some c code I use the same set up from:
https://github.com/google/googletest/blob/master/googletest/docs/primer.md#test-fixtures-using-the-same-data-configuration-for-multiple-tests. The c code to be tested is as such:
static struct {
uint32_t success;
uint32_t errors;
}stats;
uint32_t get_errors(void)
{
return stats.errors;
}
uint32_t get_success(void)
{
return stats.success;
}
void increment_errors(void)
{
stats.errors++;
}
void increment_success(void)
{
stats.success++;
}
void main_function(int arg)
{
if (arg >=0)
increment_success();
else
increment_errors();
}
Now when I write unit tests for this as such:
class MyTest : public ::testing::Test
{
protected:
void SetUp(void)
{
}
void TearDown(void)
{
}
};
TEST_F(MyTest, Test1)
{
main_function(1);
EXPECT_EQ(1, decoder_get_success());
EXPECT_EQ(0, decoder_get_errors());
}
TEST_F(MyTest, Test2)
{
main_function(40);
EXPECT_EQ(1, decoder_get_success()); //This is a fail as number ends up being 2 not 1 which includes prev. test results
EXPECT_EQ(0, decoder_get_errors());
}
Now I have noticed that when I write different test fixtures for this code the values of the stats struct variables do not reset i.e. if first test is supposed to increment success number then when we start the second test the number of success = 1 not 0 and so on and so forth. I find this behavior odd as I assumed it is supposed to reset everything with each test.
To solve this issue I ended up adding the following function to c code:
void stats_init(void)
{
decoder_stats.errors = 0;
decoder_stats.success = 0;
}
and add this to the TearDown():
void TearDown(void)
{
stats_init();
}
This makes sure that all gets reset. The question here is this the correct behavior for gtests when using test fixtures? Am I wrong to assume that it should not require m to define the init() function and add it to TearDown()?
The correct behavior of gtest is to create a new and fresh MyTest instance for each TEST_F you defined.
So, by defining a member attribute in the test fixture you are sure that you will have a different instance of your member attribute in each TEST_F
Unfortunetly, you are testing a static variable which is instanciate once. gtest does not magically known about it. So, yes, you have to reset the value of your static structure between each TEST_F.
Personnally, I will use SetUp() instead of TearDown to call stats_init.

Design for following situation having gtest procedure

In my current implementation i have 2 files (i am stuck and not getting any further)
//firstFile.cpp
class first
{
//some object of xyz class
};
first f; //global
TEST(Suite, Testcase
{
//do something
}
//secondFile.cpp
class second
{
public:
//some data members
void function()
}
Task :- I want to call TEST (consider it a special function, when it is called, object of first (i.e. global object defined will be created). In test i want to save some data for latter processing, which obviously i can't do in first class as it will be initialized on every TEST call.
Problem :- I though of having a separate class (in another .cpp file) which have required data structure to be saved. I want a way to access those data structure in TEST procedure and keep on adding the data over previous data with every TEST call. I can't have an object for second class in firstFile.cpp as it will also be created/destroyed on every call.
Any suggestion? Also i can't do anything about TEST procdedure, this is the way it is.
In gtest you can define test fixtures. It's a bit like defining a context for a set of tests. It gives you means to SetUp/TearDown stuff before/after each of your tests, but also before/after your test suite runs. Note that SetUp and TearDown are case sensitive.
struct MyFixture : testing::Test
{
private:
// stuff
protected:
//! Called before running all tests
static void SetUpTestCase();
//! Called after running all tests
static void TearDownTestCase();
//! Called before each test
void SetUp() {}
//! Called after each test
void TearDown() {}
public:
static SomeSharedObject& GetSharedObjInTest() {}
};
and in the test case you would need to call
TEST_F(MyFixture, MyTest_Name)
{
// some cool stuff here
}
You could simply create a static instance of first inside that fixture, initialize it inside SetUp() and use a static getter to access it from inside your different tests.
refer to the documentation gtest - Sharing resources between tests in the same test case

GMock: Overriding a default expectation

In GMock, is it possible to replace a previously set expectation?
Assume, a test suite has a default expectation for a specific method call, which is what most test cases want:
class MyClass {
public:
virtual int foo() = 0;
};
class MyMock {
public:
MOCK_METHOD0(foo, int());
};
class MyTest: public Test {
protected:
void SetUp() {
EXPECT_CALL(m_mock, foo()).WillOnce(Return(1));
}
MyMock m_mock;
};
TEST_F(MyTest, myTestCaseA) {
EXPECT_EQ(1, m_mock.foo());
}
This is working fine. Some of the test cases, however, have different expectations. If I add a new expectation, as shown below, it does not work.
TEST_F(MyTest, myTestCaseB) {
EXPECT_CALL(m_mock, foo()).WillOnce(Return(2));
EXPECT_EQ(2, m_mock.foo());
};
I get this message:
[ RUN ] MyTest.myTestCaseB
/home/.../MyTest.cpp:94: Failure
Actual function call count doesn't match EXPECT_CALL(m_mock, foo())...
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] MyTest.myTestCaseB (0 ms)
I understand why I am getting this. The question is how to cancel the default expectation, if a test case specifies its own? Does GMock allow it or what approaches can I use to achieve the intended behaviour?
No, there's no way to clear an arbitrary expectation. You can use VerifyAndClearExpectations to clear all of them, that's probably more than you want. I can think of several alternatives that avoid the issue:
You could work around your problem by simply calling m_mock.foo() once in advance, thus fulfilling the initial expectation.
TEST_F(MyTest, myTestCaseB) {
EXPECT_CALL(m_mock, foo()).WillOnce(Return(2));
(void)m_mock.foo();
EXPECT_EQ(2, m_mock.foo());
}
Another alternative is to change the expectation to have it return the value of a variable, then then update the variable prior to the test body, as described in the cookbook under Returning Live Values from Mock Methods. For example:
void SetUp() {
m_foo_value = 1;
EXPECT_CALL(m_mock, foo()).WillOnce(Return(ByRef(m_foo_value)));
}
TEST_F(MyTest, myTestCaseB) {
m_foo_value = 2;
EXPECT_EQ(2, m_mock.foo());
}
Yet another alternative is to specify the return value and the count separately.
void SetUp() {
ON_CALL(m_mock, foo()).WillByDefault(Return(1));
EXPECT_CALL(m_mock, foo()).Times(1);
}
Then, you only need to specify a new return value for the special test:
TEST_F(MyTest, myTestCaseB) {
ON_CALL(m_mock, foo()).WillByDefault(Return(2));
EXPECT_EQ(2, m_mock.foo());
}