当没有默认构造函数时如何在Googletest固定装置中定义变量?

问题描述 投票:0回答:1

我有以下内容


#include <semsim/Subject.h>
#include <semsim/Triple.h>
#include "gtest/gtest.h"

class TripleTests : public ::testing::Test {
public:

    std::string subject_str;
    semsim::Subject subject;

    void SetUp() override {
        subject_str = "./MyModel#metaid_0";
        subject = semsim::Subject(subject_str);
    }
};

TEST_F(TripleTests, TestSubjectMetaId) { // this line causes the error
    std::cout << subject << std::endl;
}

为了定义变量(以供以后在TEST_F函数中使用),必须在类范围中创建它们,然后在SetUp方法中填充一个值。这是因为我无法在课程级别将subject_str传递给Subject。但是,如果在类级别实例化一个变量,它将使用默认构造函数,而我的类没有(也不需要)一个。这是我的IDE的投诉:

Call to implicitly-deleted default constructor of 'TripleTests' because field 'subject' has no default constructor

[因此,我的问题:无需定义默认构造函数,我如何在TripleTest类中创建主题对象,以便可以在TEST_F函数中使用它?还是有必要在Suject中默认构造函数,以便我可以在测试夹具中创建一个构造函数?

供参考,Subject标头看起来像这样:

    class Subject {
    private:
        std::string metaId;

    public:

        explicit Subject(std::string metaId) : metaId(std::move(metaId)) {};

        const std::string &getMetaId() const;

        bool operator==(const Subject &rhs) const;

        bool operator!=(const Subject &rhs) const;

        friend std::ostream &operator<<(std::ostream &os, const Subject &subject);
    };

}

编辑

@ Tomasz的回答


class TripleTests : public ::testing::Test {
public:

    std::string subject_str;
    semsim::Subject subject;
    // alternative 1
    TripleTests()  {
        this->subject_str = "./MyModel#metaid_0";
        semsim::Subject s(subject_str);
        this->subject = s;
    }

    // alternative 2
    TripleTests()  {
        this->subject_str = "./MyModel#metaid_0";
        this->subject = semsim::Subject(subject_str);
    }

结果]

Constructor for 'TripleTests' must explicitly initialize the member 'subject' which does not have a default constructor. Isn't the line `this->subject = s` initialising the member `subject`? 

我有以下#include #include #include“ gtest / gtest.h”类TripleTests:public :: testing :: Test {public:std :: string subject_str; ...

c++ googletest
1个回答
0
投票

您必须使用夹具的构造函数而不是SetUp()来初始化初始化器列表中的成员:

热门问题
推荐问题
最新问题