Testing a class with a non-zero argument constructor in Google Test

Of all the C++ testing libraries I googled for, the most powerful and easiest to use seems to be… er… Google’s πŸ™‚

Me being mostly a Java/Python programmer (and proud to be!), I still can’t find it “easy” but… it’s mostly like using JUnit (well, mostly).

You get your SetUp() and TearDown() functions, your ::testing::Test class to extend and your TEST_F()s with all their EXPECT_whatever() to be run stuffing ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); into your main() function.

Ok, the first test I wrote actually shattered my “oh-my-it’s-just-like-JUnit!” dream.. I just wanted to write a test for a class that needs a std::string as argument. The easiest way I found to do that is to have your test class extend the class under test, and wrap the super class constructor with a no-args one.

Here’s what I did:

#include "gtest/gtest.h"
#include "my_class.h"

using namespace std;

class MyClassTest: public ::testing::Test, public MyClass {
    static string test_path_;
    string pathname() {
      return pathname_; // as it's a protected field in MyClass
    MyClassTest() :
      MyClass(test_path_) {
    virtual void SetUp() {
      my_class_test_ = this;
    MyClassTest* my_class_test_;

string MyClassTest::test_path_ = "test";

// Tests that MyClass constructor sets the correct path
TEST_F(MyClassTest, Constructor) {
  EXPECT_STREQ("test", my_class_test_->pathname().c_str());

Of course this is just a toy to understand the framework, but it’s a little example I couldn’t easily find on the web right now..
I’m no C++ expert at all, so if anyone reading this feels insulted by something I wrote, please, please post a comment and teach me how this should be done, I’m more than willing to learn! πŸ™‚

[Update – July 2013]: Mark Abraham posted how it’s done, just scroll down to his comment!


2 thoughts on “Testing a class with a non-zero argument constructor in Google Test

  1. You need to derive from MyClass to get access to the protected pathname_ (e.g. give it a public getter function), but you do not need to derive from ::testing::Test – or even need a test fixture.

    In the TEST(), construct a DerivedFromMyClass in a way that calls the MyClass(std::string) constructor you want to test, and then compare the result from the getter with what it should be.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s