CppUnit 中类似于 TestFixtureSetUp 的方法
在 NUnit 中,TestFixtureSetup 属性可用于标记应在夹具中的任何测试之前执行一次的方法。
CppUnit 中有类似的概念吗?
如果没有,是否有支持这个概念的 C++ 单元测试框架?
根据下面的答案,这里是一个实现此目的的示例(遵循 这个问题):
// 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();
}
};
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();
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您无法使用固定构造函数,这意味着 CPPUnit 在每个测试中都使用实例。我认为您必须有一个方法和一个静态布尔标志,该标志可以多次读取并且仅在第一次写入。然后在构造函数中调用它。
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.