C++单元测试-构造函数中出现抛出错误的测试类



我在用不依赖于我的成员变量测试类时遇到问题。我的意思是,该类包含一个从其他文件中包含的变量。这个类在构造函数中抛出错误(不管为什么(。然后我有一个函数,它使用这个变量。那么我应该如何测试这门课呢?

// ** classForMe.h can't modify **
class ClassForMe
{
public:
ClassForMe(){
// not relevant what should be here but throw error in this case
throw std::runtime_error("");
}
int getData()const {return data;}
...
private:
int data;
};

包含我的类的其他文件

// C.hpp
#include <classForMe.h>
class C
{
public:
C():classForMe{}{}
void save(){
//some code here, but i need data from ClassForMe
int i = classForMe.getData();
...
}
private:
ClassForMe classForMe;
};

如果我没有清楚地解释我的问题,有人想";为什么要测试抛出错误的代码;。这段代码运行良好,但在我的平台上不起作用。对我来说,它抛出了错误,所以可能对这个类进行写测试吗?例如,我模拟了那个类ForMe构造得很好,并且包含一些值?然后这个值将用于测试方法void save((

#include <gtest/gtest.h>
#include "C.hpp"
class C_test  : public ::testing::Test
{
... ?? 
};

为了测试类C,我会使用高性能依赖注入来模拟ClassForMe(或者如果您可以创建一个抽象的ClassForMe接口类,并且所有方法都是纯虚拟的,则使用常规依赖注入(。通过这种方式,您可以在测试中设置对ClassForMe类的期望值,例如调用savegetData的不同返回值。

struct ClassForMe{
int getData() const;
};
template<class IMPL = ClassForMe>
class C
{
public:
C(IMPL& impl):classForMe{impl}{}
void save(){
//some code here, but i need data from ClassForMe
int i = classForMe.getData();
std::cout << "i is " << i;
//...
}
private:
IMPL& classForMe;
};
struct ClassForMeMock {
MOCK_METHOD0(getData, int());
};
class C_test  : public ::testing::Test
{
public:
ClassForMeMock mock{};
C<ClassForMeMock> c{mock};
};
TEST_F(C_test, SomeTest) {
EXPECT_CALL(mock, getData()).WillOnce(testing::Return(42));
c.save(); // will print "i is 42" to stdout
}

相关内容

最新更新