如何使用 SFML 和 cmake 进行增强测试?

How to use boost tests with SFML and cmake?

我正在使用 SFML 用 C++ 编写一个简单的游戏。我想使用增强测试,但是当我尝试在我使用 SFML 功能的每个地方都获得未定义的引用时(游戏本身运行良好,只是测试没有)。样本测试:

#include <boost/test/unit_test.hpp>
#include "Sentry.h"

BOOST_AUTO_TEST_SUITE(BasicModelTestSuite)

BOOST_AUTO_TEST_CASE(testLamp_10BulbsWithPower10_ExpectedPower)
    {
        sf::Texture projectileTexture;
        sf::Texture sentryTexture;
        std::vector<std::shared_ptr<Sentry>> foes;
        sentryTexture.loadFromFile("../GameResources/sentry_image.png");
        projectileTexture.loadFromFile("../GameResources/projectile_animation.png");
        foes.push_back(std::make_shared<Sentry>(Sentry(&sentryTexture, sf::Vector2u(1,2), 0.2f, sf::Vector2f(140,200), projectileTexture, true)));
        foes.push_back(std::make_shared<Sentry>(Sentry(&sentryTexture, sf::Vector2u(1,2), 0.2f, sf::Vector2f(200,200), projectileTexture, false)));
        BOOST_REQUIRE_EQUAL(foes.size(), 2);
    }

BOOST_AUTO_TEST_SUITE_END()

和cmakelist.txt的测试部分:

ind_package(Boost 1.65 COMPONENTS "unit_test_framework" REQUIRED)

include_directories(
        ${CMAKE_CURRENT_SOURCE_DIR}/include
        ${Boost_INCLUDE_DIRS}
)

set(SOURCE_TEST_FILES
        test/master.cpp test/master.cpp test/baseTest.cpp
        main.cpp src/Level.cpp include/Level.h src/Game.cpp include/Game.h src/Platform.cpp include/Platform.h src/Item.cpp include/Item.h src/Life.cpp include/Life.h src/Coin.cpp include/Coin.h src/Collider.cpp include/Collider.h src/Enemy.cpp include/Enemy.h src/MrStrawberry.cpp include/MrStrawberry.h src/Animation.cpp include/Animation.h src/MrBerry.cpp include/MrBerry.h src/Projectile.cpp include/Projectile.h src/Sentry.cpp include/Sentry.h)

add_executable(TestProject ${SOURCE_TEST_FILES})

target_include_directories(TestProject PUBLIC include)

target_link_libraries(TestProject
        ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY})

enable_testing()

add_test(NAME Test COMMAND TestProject
        --report_level=detailed
        --log_level=all
        --color_output=yes)

add_custom_target(check ${CMAKE_COMMAND} -E env CTEST_OUTPUT_ON_FAILURE=1 BOOST_TEST_LOG_LEVEL=all
        ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> --verbose
        WORKING_DIRECTORY ${CMAKE_BINARY_DIR})

我不知道为什么它会抛出对所有内容的未定义引用,如下所示:

/usr/bin/ld: /home/student/CLionProjects/oop21_ww2_14/BerryGame/src/Projectile.cpp:8: undefined reference to `sf::RectangleShape::setSize(sf::Vector2<float> const&)'
/usr/bin/ld: /home/student/CLionProjects/oop21_ww2_14/BerryGame/src/Projectile.cpp:9: undefined reference to `sf::Shape::setTexture(sf::Texture const*, bool)'

TestProject 在 link 选项中缺少 SFML 库(另请参阅 What is an undefined reference/unresolved external symbol error and how do I fix it?)。您的主要可执行文件显然 有它,但您没有显示它。

寻找类似

的内容
 LINK_LIBRARIES(sfml-system sfml-window sfml-graphics sfml-audio)

或 target_link_libraries 代替。如果使用 LINK_LIBRARIES,我想目标可能需要在 之后定义。