C++ unit test - Test class with throwed error in constructor

半腔热情 提交于 2021-02-08 10:01:52

问题


I have a problem with testing class with member variable which is not dependent on me. I mean the class contain a variable that is include from other file. And this class throwing error in constructor(no matter why). And then I have a function that uses this variable. So how should I test this class?

// ** 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;
};

other file which contain my class

// 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;
};

If I not clear explained my problem and someone thinking "why you want to testing code which throwing error". This code working well, but not in my platform. For me it throwing error so is posible write test for this class e.g. i emulate that classForMe is construt well and contain some value? And then this value will be used in test of method void save()?

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

回答1:


In order to test your class C I'd use hi-perf dependency injection to mock ClassForMe (or regular dependency injection if you can create an abstract ClassForMe interface class with all the methods pure virtual). This way you can set expectations for the ClassForMe class in your tests - e.g. different return values of getData when save is called.

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
}


来源:https://stackoverflow.com/questions/64929208/c-unit-test-test-class-with-throwed-error-in-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!