C++ Boost.Test - Where should class object be created to test it's method?

2.6k views Asked by At

I am doing exercism.io C++ challenges which use Boost to test the code. I have 3 files, bob.cpp, bob.h, and bob_test.cpp(all below). Without classes, I can get the tests to run fine. But once I need to test a class method, like in bob_test.cpp, which attempts to test bob::hey([arg]), then I get the error:

error: cannot call member function ‘std::__cxx11::string bob::hey()’ without object

So I clearly need to instantiate bob somewhere(Ex: bob bob; ... I didn't choose the names) but I just can't figure out where to do it. The Boost test framework provides it's own main function(which means I don't provide one), so I can't do it there, and I kind of expected that Boost would instantiate the object itself, but it doesn't seem to. I have tried inserting bob bob; into bob_test.cpp and bob.cpp resulting in the same error. My question is, where should I then instantiate a bob object that can be used in bob_test.cpp? Being a C++ noob, my gut says it should be in bob_test.cpp, but I'm also pretty confident I'm not supposed to edit that file.

bob.cpp

#include "bob.h"
#include <iostream>
#include <string>

using namespace std;


string bob::hey() {
    return "Whatever.";
}

bob.h

#include <iostream>
#include <string>

// bob.h
class bob {

    public:

    std::string hey();

};

bob_test.cpp(just providing the first test(simplified) causing the error, the actual test is slightly different, I just want to get the setup working)

#include "bob.h"
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>


BOOST_AUTO_TEST_CASE(stating_something)
{
    BOOST_REQUIRE_EQUAL("Whatever.", bob::hey());
}
2

There are 2 answers

2
Edward Strange On

hey is a non-static member function and you're trying to use it as a static. You need to create an object. This is C++ bitching at you, not Boost.

bob mybob;
mybob.hey();

You could also just do this: bob().hey()

1
kenba On

You could use a boost::test fixture to create an instance of class bob and then test bob's functions in separate test cases, see: Fixture models. E.g.:

#include "bob.h"
#include <boost/test/unit_test.hpp>

struct TestFixture
{
  bob bob_instance;

  TestFixture()
  : bob_instance()
  {}

  ~TestFixture() = default;
}

BOOST_FIXTURE_TEST_SUITE(TestBob, TestFixture)

BOOST_AUTO_TEST_CASE(stating_something)
{
   BOOST_REQUIRE_EQUAL("Whatever.", bob_instance.hey());
}

BOOST_AUTO_TEST_SUITE_END()