c++ - 无法引用测试夹具的默认构造函数

标签 c++ unit-testing visual-studio-2015 googletest default-constructor

我在使用 Visual Studio 2015 中的 Google Test 编译带有测试夹具的文件时遇到问题。我尝试为其创建测试夹具的类名为 Counter

被测计数器类有一个 protected 默认构造函数,用于初始化各种 protected 成员变量。 Counter 类中的这些成员变量包括对象、指向 const 对象的指针、int 和 double。

DefaultConstructor 测试无法编译并显示以下错误消息 无法引用“CounterTest”的默认构造函数 -- 它是一个已删除的函数

为了清楚起见,我试图在 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_);
}

我做错了什么?是否有可能让测试夹具与正在测试 protected /私有(private)成员访问的类成为 friend ?谢谢!

最佳答案

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

class Counter
{
public:
    int numStarts_;
};

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

关于c++ - 无法引用测试夹具的默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38469597/

相关文章:

c# - Blazor 测试 InputDate 与 bUnit 的绑定(bind)

eclipse - 如何对 Eclipse 命令处理程序进行单元测试?

c# - 关闭通用应用程序中打开的文件

c# - 为什么编译器不推断泛型类型

c++ - nullptr 是否引用 C++ 中的未定义行为?

c++ - 节省内存的 C++ 字符串(interning、ropes、copy-on-write 等)

c++ - "Curiously Recurring Template Pattern"的实际用途

c++ - OpenCV 3 中的 FLANN 错误

unit-testing - Racket 哈希相等

c++ - cmake 不可见 Visual Studio 编译器