【问题标题】:Default constructor of test fixture cannot be referenced无法引用测试夹具的默认构造函数
【发布时间】:2023-03-28 23:40:01
【问题描述】:

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

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

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_);
}

我做错了什么?甚至可以让测试夹具与正在测试受保护/私有成员访问的类成为朋友吗?谢谢!

【问题讨论】:

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


    【解决方案1】:

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

    class Counter
    {
    public:
        int numStarts_;
    };
    

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

    【讨论】:

    • 我没有向 CounterTest 类添加非默认构造函数。我没有在上面显示的 CounterTest 类中留下任何东西,这正是我的实际代码中的样子。自从您发表评论以来,我也向 Counter 类添加了一些额外的接口细节。
    【解决方案2】:

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

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

    };

    【讨论】:

      猜你喜欢
      • 2021-04-02
      • 1970-01-01
      • 2013-02-11
      • 2014-10-05
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多