如何在Google Test中为一个灯具运行多个测试用例?

时间:2016-07-05 16:32:06

标签: c++ qt unit-testing testing googletest

假设我有一个名为ProfileTest的Google测试夹具,它继承自::testing::TestWithParams<T>,可创建解析器:

class ProfileTest:

public ::testing::TestWithParam<std::tuple<std::string,std::string>>{

public:
    QString getName(){
        return QFileInfo(*m_file).fileName();
    }

protected:
    void SetUp(){

        m_profile = new Profile();

        m_file = new QFile(std::get<0>(GetParam()).c_str());
        m_file->open(QIODevice::WriteOnly | QIODevice::Text);
        m_file->write(std::get<1>(GetParam()).c_str());
        m_file->close();

    }
    void TearDown(){

        delete m_file;

        delete m_profile;
    }

    Profile* m_profile;
    QFile *m_file;
};

参数化测试用例:

TEST_P(ProfileTest, TestProfileGoodFormedContent){
    ASSERT_NO_THROW(m_profile->readProfile(QFileInfo(*m_file)));
    ASSERT_STREQ(m_profile->name(), getName());
    ASSERT_GE(m_profile->getProfileConfigurations().size(),1);
}

我添加了TEST_CASE内容完善的内容,而且效果很好。

现在我想添加TEST_CASE内容不正确的内容,但TestProfileGoodFormedContent TEST_P不适合测试不良内容。

我想我应该添加一个新的TEST_P,但它会有相同的fixture(ProfileTest),这会给我一个错误,即所有测试用例都会提供给TEST_P ProfileTest作为夹具。

如何同时测试格式良好的内容和格式错误的内容?

1 个答案:

答案 0 :(得分:3)

在您的情况下,您需要尽可能多的Google测试装置,因为您有不同的方案。

当然,您可以拥有基础夹具类 - 这将为您设置常见的东西:

class ProfileTestBase :

public ::testing::TestWithParam<std::tuple<std::string,std::string>>{

public:
    QString getName(){
        return QFileInfo(*m_file).fileName();
    }

protected:
    void SetUp(){

        m_profile = new Profile();

        m_file = new QFile(std::get<0>(GetParam()).c_str());
        m_file->open(QIODevice::WriteOnly | QIODevice::Text);
        m_file->write(std::get<1>(GetParam()).c_str());
        m_file->close();

    }
    void TearDown(){

        delete m_file;

        delete m_profile;
    }

    Profile* m_profile;
    QFile *m_file;
};

所以 - 基本上你当前的类将成为基类。

对于Good / Bad / Whatever-else - 创建特定的夹具类:

class GoodProfileTest : public ProfileTestBase {};
class BadProfileTest : public ProfileTestBase {};

您当前的“好”个人资料测试属于GoodProfileTest:

TEST_P(GoodProfileTest, TestProfileGoodFormedContent){
    ASSERT_NO_THROW(m_profile->readProfile(QFileInfo(*m_file)));
    ASSERT_STREQ(m_profile->name(), getName());
    ASSERT_GE(m_profile->getProfileConfigurations().size(),1);
}

无论您需要测试什么是错误的个人资料 - 请使用BadProfileTest类。等等......当然 - 你需要为每个灯具使用INSTANTIATE _ ***宏。