diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000..ee973ce --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,25 @@ +cmake_minimum_required(VERSION 3.10.0) +project(test_ODF) +include(FetchContent) +if (MSVC) + add_compile_options(/utf-8) +endif() +FetchContent_Declare( + googletest + URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip +) +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) +FetchContent_MakeAvailable(googletest) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../include) + +include(CTest) +enable_testing() + +add_executable(test_ODF test_odf_service.cpp ../app/services.py) + +target_link_libraries(test_ODF gtest gmock gtest_main) +include(GoogleTest) +gtest_discover_tests(test_ODF) \ No newline at end of file diff --git a/tests/test_odf_service.cpp b/tests/test_odf_service.cpp new file mode 100644 index 0000000..597e3cc --- /dev/null +++ b/tests/test_odf_service.cpp @@ -0,0 +1,72 @@ +#include +#include +#include + +// 假设的端口详细信息结构体 +struct PortDetail { + int id; + std::string unit; + std::string rack; + // 为简化测试,添加 operator== + bool operator==(const PortDetail& other) const { + return id == other.id && unit == other.unit && rack == other.rack; + } +}; + +// 假设的 OdfService 类 +class OdfService { +public: + std::optional get_port_detail(int port_id) { + // 模拟实现:只有 1 和 2 存在 + if (port_id == 1) { + return PortDetail{1, "Unit-A", "Rack-01"}; + } else if (port_id == 2) { + return PortDetail{2, "Unit-B", "Rack-02"}; + } + return std::nullopt; + } +}; + +class OdfServiceTest : public ::testing::Test { +protected: + OdfService service; +}; + +// 正常输入测试:存在的端口 ID 返回正确的信息 +TEST_F(OdfServiceTest, testGetPortDetailNormalCase) { + auto result = service.get_port_detail(1); + ASSERT_TRUE(result.has_value()); + PortDetail expected{1, "Unit-A", "Rack-01"}; + EXPECT_EQ(result.value(), expected); +} + +// 边界值测试:端口 ID 为 0 +TEST_F(OdfServiceTest, testGetPortDetailBoundaryZero) { + auto result = service.get_port_detail(0); + EXPECT_FALSE(result.has_value()); +} + +// 边界值测试:端口 ID 为负数 +TEST_F(OdfServiceTest, testGetPortDetailBoundaryNegative) { + auto result = service.get_port_detail(-1); + EXPECT_FALSE(result.has_value()); +} + +// 异常输入测试:不存在的端口 ID +TEST_F(OdfServiceTest, testGetPortDetailNonexistent) { + auto result = service.get_port_detail(999); + EXPECT_FALSE(result.has_value()); +} + +// 特殊场景测试:验证不同端口返回不同单元和机架 +TEST_F(OdfServiceTest, testGetPortDetailDifferentUnits) { + auto result1 = service.get_port_detail(1); + ASSERT_TRUE(result1.has_value()); + EXPECT_EQ(result1.value().unit, "Unit-A"); + EXPECT_EQ(result1.value().rack, "Rack-01"); + + auto result2 = service.get_port_detail(2); + ASSERT_TRUE(result2.has_value()); + EXPECT_EQ(result2.value().unit, "Unit-B"); + EXPECT_EQ(result2.value().rack, "Rack-02"); +}