2009-12-21 70 views
2

我遇到了升压单元测试问题。基本上我创建了一个夹具,它是套件的一部分,用于测试资源缓存。我的主要问题是测试资源缓存变空了。因此,测试缓存的第一个测试通过,然后第二个测试失败,因为插入缓存的第一个测试数据不再存在。为了解决这个问题,我必须重新插入第二次测试的数据。这是打算或是我做错了什么?这是代码。最后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()

回答

7

它是有意的。单元测试的关键原理之一是每个测试都是独立运行。应该给它一个干净的环境来运行,并且之后应该再次清理环境,以便测试不依赖于其他环境。

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

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

+0

感谢一群人,只是想确保我不会发疯。 – blewisjr 2009-12-21 21:37:48