在NUnit中,TestFixtureSetup属性可用于标记在夹具中的任何测试之前应执行一次的方法。
CppUnit中是否有类似的概念?
如果没有,是否有支持这一概念的C ++单元测试框架?
根据下面的答案,这是一个实现这一点的例子(遵循this问题答案的建议):
// 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();
}
};
答案 0 :(得分:0)
由于您无法使用fixture构造函数,这意味着CPPUnit正在使用每个测试的实例。我想你必须有一个方法和一个静态布尔标志,它被多次读取并且只在第一次写入。然后在构造函数中调用它。