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

C++ C++;单元测试-构造函数中出现抛出错误的测试类,c++,unit-testing,googletest,C++,Unit Testing,Googletest,我在使用成员变量测试类时遇到了一个问题,该变量不依赖于我。我的意思是该类包含一个从其他文件中包含的变量。这个类在构造函数中抛出错误(不管为什么)。然后我有一个使用这个变量的函数。那么我应该如何测试这个类呢 // ** classForMe.h can't modify ** class ClassForMe { public: ClassForMe(){ // not relevant what should be here but throw error in this case

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

// ** 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;
};
//C.hpp
#包括
C类
{
公众:
C():classForMe{}{}
作废保存(){
//这里有一些代码,但我需要ClassForMe中的数据
int i=classForMe.getData();
...
}
私人:
ClassForMe ClassForMe;
};
如果我不清楚地解释了我的问题,有人在想“为什么要测试哪一个抛出错误的代码”。 这段代码运行良好,但在我的平台上不起作用。对我来说,这是一个错误,所以这个类有可能进行写测试,例如,我模拟classForMe结构良好并包含一些值? 然后该值将用于测试方法void save()

#include <gtest/gtest.h>
#include "C.hpp"
class C_test  : public ::testing::Test
{
 ... ?? 
};
#包括
#包括“C.hpp”
C类测试:公共::测试::测试
{
... ?? 
};

为了测试你的类
C
我会使用mock
ClassForMe
(或者如果你能用纯虚拟的方法创建一个抽象的
ClassForMe
接口类,则使用常规的依赖注入)。通过这种方式,您可以在测试中设置
ClassForMe
类的期望值-例如,调用
save
getData
的不同返回值

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
}
struct ClassForMe{
int getData()常量;
};
模板
C类
{
公众:
C(IMPL&IMPL):classForMe{IMPL}{
作废保存(){
//这里有一些代码,但我需要ClassForMe中的数据
int i=classForMe.getData();

std::cout伪造测试有什么意义?如果你不在乎,你就不能不运行测试或删除它吗?我同意molbnilo的观点。如果该测试不打算通过,那么你就不应该运行它。如果它不在你的平台上运行,而是在其他平台上运行,那么你应该在你的平台上编译时有条件地删除该测试。重点是测试方法是否保存().但在我的情况下,我在测试环境中没有组件,这是必要的,可以毫无错误地构造classForMe。所以我想用不是来自classForMe的值来测试它。因为我知道这个classForMe在适当的环境中会构造得很好,但当我得到这个组件时,我必须检查我的C类中的方法save是否工作得很好用于在没有错误的情况下破坏ClassForMe。然后适当的操作过程是重构。我这样做了,正如您所描述的。但是在带有测试的文件中,我得到了关于对该模拟对象的未定义引用的错误。“未定义对C::save()的引用”和“未定义对C::C的引用(ClassForMeMock&”)'我在我的cpp文件中将构造函数和方法定义为:template`C::C(T&T):classForMe{T}{}template void C::save(){/…}/…模板类C;`我想我需要在这里添加更多内容?如果您切换到基于模板的方法,我不认为您可以在cpp中定义
save
——除非您预先知道类型,否则您可以在cpp文件中定义模板,请参见。否则,
类C
必须仅在标题中。