1

我在使用Visual Studio 2015中的Google Test测试夹具编译文件时出现问题。我尝试创建测试夹具的类名为计数器测试夹具的默认构造函数不能被引用

被测计数器类有一个受保护的默认构造函数,用于初始化各种受保护的成员变量。 Counter类中的这些成员变量包括对象,指向const对象的指针,整数和双精度。

DefaultConstructor测试失败,编译时出现以下错误消息the default constructor of "CounterTest" cannot be referenced -- it is a deleted function

要清楚,我试图在CounterTest类(测试夹具)中实例化一个Counter对象(使用它的默认构造函数)以跨个别测试使用。

// Counter.h 
class Counter : public ConfigurationItem { 
protected: 
    EventId startEventIdIn_; 
    int numStarts_; 
    CounterConfigurationItem_Step const* currentStep_; 
    double startEncoderPosMm_; 
private: 
    FRIEND_TEST(CounterTest, DefaultConstructor); 
}; 

// GTest_Counter.cpp 
class CounterTest : public ::testing::Test { 
protected: 
    Counter counter; 
}; 

TEST_F(CounterTest, DefaultConstructor) 
{ 
    ASSERT_EQ(0, counter.numStarts_); 
} 

我在做什么错?是否有可能让一个测试夹具成为正在测试受保护/私人成员访问的类的朋友?谢谢!

回答

0

我猜你没有张贴CounterTest类的完整定义,因为你已经发布的代码编译没有错误,如果我添加一个虚拟Counter类:

class Counter 
{ 
public: 
    int numStarts_; 
}; 

由于错误信息表明,有是类CounterTest没有默认的构造函数,我猜你已经添加了一个非默认构造函数的类。在C++中,这意味着如果你没有明确指定默认构造函数,它将被删除。这是一个问题,因为googletest仅使用默认构造函数实例化测试夹具类,您不能使用非默认构造函数来实例化测试夹具。如果您需要在每次测试之前执行一些不同的操作,您可以将带有参数的SetUp方法版本添加到夹具类中,并在每次测试开始时用期望的输入参数调用它。

+0

我还没有添加一个非默认的构造函数** CounterTest **类。我没有从上面显示的** CounterTest **类中除去任何内容,这与我的实际代码完全相同。自你的评论以来,我已经为Counter类添加了一些额外的界面细节。 – GnUfTw

0

解决方案:将CounterTest声明为朋友类。

class Counter : public ConfigurationItem { 
protected: 
    EventId startEventIdIn_; 
    int numStarts_; 
    CounterConfigurationItem_Step const* currentStep_; 
    double startEncoderPosMm_; 
private: 
    friend class CounterTest; 
    FRIEND_TEST(CounterTest, DefaultConstructor); 

};

相关问题