【问题标题】:Boost Test Fixture object clearing between tests提升测试夹具对象清除测试之间
【发布时间】:2009-12-21 21:27:43
【问题描述】:

我遇到了 boost 单元测试的问题。基本上,我创建了一个固定装置,它是对资源缓存进行单元测试的套件的一部分。我的主要问题是在测试之间资源缓存变空。因此,测试缓存的第一个测试通过,然后第二个测试将失败,因为第一个测试插入缓存的数据不再存在。为了解决这个问题,我不得不为第二次测试重新插入数据。这是故意的还是我做错了什么?这是代码。最后 2 个测试是问题所在。


#include "UnitTestIncludes.hpp"
#include "ResourceCache.hpp"
#include <SFML/Graphics.hpp>

struct ResourceCacheFixture
{
    ResourceCacheFixture()
    {
        BOOST_TEST_MESSAGE("Setup Fixture...");
        key = "graysqr";
        imgpath = "../images/graysqr.png";
    }

    ResourceCache<sf::Image, ImageGenerator> imgCache;
    std::string key;
    std::string imgpath;
};

// Start of Test Suite

BOOST_FIXTURE_TEST_SUITE(ResourceCacheTestSuite, ResourceCacheFixture)

// Start of tests

BOOST_AUTO_TEST_CASE(ImageGeneratorTest)
{
    ImageGenerator imgGen;
    BOOST_REQUIRE(imgGen("../images/graysqr.png"));

}

BOOST_AUTO_TEST_CASE(FontGeneratorTest)
{
    FontGenerator fntGen;
    BOOST_REQUIRE(fntGen("../fonts/arial.ttf"));
}

// This is where the issue is.  The data inserted in this test is lost for when I do
// the GetResourceTest.  It is fixed here by reinserting the data.
BOOST_AUTO_TEST_CASE(LoadResourceTest)
{
    bool result = imgCache.load_resource(key, imgpath);
    BOOST_REQUIRE(result);
}

BOOST_AUTO_TEST_CASE(GetResourceTest)
{
    imgCache.load_resource(key, imgpath);
    BOOST_REQUIRE(imgCache.get_resource(key));
}

// End of Tests

// End of Test Suite
BOOST_AUTO_TEST_SUITE_END()

【问题讨论】:

    标签: c++ unit-testing boost


    【解决方案1】:

    这是有意的。单元测试的关键原则之一是每个测试独立运行。应该给它一个干净的运行环境,然后再清理这个环境,这样测试就不会相互依赖。

    使用 Boost.Test,您可以指定从命令行运行哪些测试,因此您不必运行整个套件。如果您的测试相互依赖,或者依赖于它们的执行顺序,那么这将导致测试失败。

    夹具旨在设置运行测试所需的环境。如果您需要在测试运行之前创建资源,夹具应该创建它们,然后再次清理它们。

    【讨论】:

    • 谢谢一堆只是想确保我没有发疯。
    猜你喜欢
    • 1970-01-01
    • 2018-08-06
    • 2021-12-01
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多