tags:

views:

25

answers:

1

In NUnit, the TestFixtureSetup attribute can be used to mark a method which should be executed once before any tests in the fixture.

Is there an analogous concept in CppUnit?

If not, is there a C++ unit testing framework that supports this concept?

Based on the answer below, here is an example which accomplishes this (following the advice of the answers to this question):

// Only one instance of this class is created.
class ExpensiveObjectCreator
{
public:
    const ExpensiveObject& get_expensive_object() const
    {
        return expensive;
    }

private:
    ExpensiveObject expensive;
};

class TestFoo: public CppUnit::TestFixture
{
    CPPUNIT_TEST_SUITE(TestFoo);
    CPPUNIT_TEST(FooShouldDoBar);
    CPPUNIT_TEST(FooShouldDoFoo);
    CPPUNIT_TEST_SUITE_END();

public:
    TestFoo()
    {
        // This is called once for each test
    }

    void setUp()
    {
        // This is called once for each test
    }

    void FooShouldDoBar()
    {
        ExpensiveObject expensive = get_expensive_object();
    }

    void FooShouldDoFoo()
    {
        ExpensiveObject expensive = get_expensive_object();
    }

private:
    const ExpensiveObject& get_expensive_object()
    {
        static ExpensiveObjectCreator expensive_object_creator;
        return expensive_object_creator.get_expensive_object();
    }
};
A: 

Since you cannot use the fixture constructor this implies that CPPUnit is using instance per test. I think you''ll have to have a method and a static boolean flag that is read many times and written only the first time. Then call this in the constructor.

Preet Sangha
The fixture constructor still seems to be called for every test.
Josh Peterson
Using a static seems to make sense. I'll give that a try. I still wonder if there is a better solution. This seems like a very common idiom.
Josh Peterson
Actually this is discouraged now. The en vogue idea is set up and tear down per test and one instance per test see here for more info as to why this is a good idea : http://martinfowler.com/bliki/JunitNewInstance.html and http://blogs.msdn.com/b/jamesnewkirk/archive/2004/12/04/275172.aspx
Preet Sangha
The reasoning in those articles does make sense. I have updated the example with the solution that I have used. Thanks!
Josh Peterson