60 lines
2.0 KiB
C++
60 lines
2.0 KiB
C++
|
|
#include <gtest/gtest.h>
|
|||
|
|
#include <map>
|
|||
|
|
#include <string>
|
|||
|
|
#include <chrono>
|
|||
|
|
#include <thread>
|
|||
|
|
|
|||
|
|
// 假设 HealthController 的头文件已包含,这里模拟实现
|
|||
|
|
// 因为原代码是 Java,此处仅模拟 C++ 对应逻辑的测试
|
|||
|
|
|
|||
|
|
class HealthController {
|
|||
|
|
public:
|
|||
|
|
std::map<std::string, std::string> health() {
|
|||
|
|
auto now = std::chrono::system_clock::now();
|
|||
|
|
auto time_t = std::chrono::system_clock::to_time_t(now);
|
|||
|
|
char buffer[64];
|
|||
|
|
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", std::localtime(&time_t));
|
|||
|
|
|
|||
|
|
return {
|
|||
|
|
{"status", "UP"},
|
|||
|
|
{"service", "商城管理系统"},
|
|||
|
|
{"timestamp", std::string(buffer)}
|
|||
|
|
};
|
|||
|
|
}
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
// 测试用例
|
|||
|
|
TEST(HealthControllerTest, testHealthNormalInput) {
|
|||
|
|
HealthController controller;
|
|||
|
|
auto result = controller.health();
|
|||
|
|
|
|||
|
|
EXPECT_EQ(result.at("status"), "UP");
|
|||
|
|
EXPECT_EQ(result.at("service"), "商城管理系统");
|
|||
|
|
EXPECT_FALSE(result.at("timestamp").empty());
|
|||
|
|
EXPECT_TRUE(result.at("timestamp").length() >= 19); // YYYY-MM-DD HH:MM:SS
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
TEST(HealthControllerTest, testHealthBoundaryValues) {
|
|||
|
|
HealthController controller;
|
|||
|
|
auto result = controller.health();
|
|||
|
|
|
|||
|
|
// 验证时间戳格式是否合理(边界值检查)
|
|||
|
|
const std::string& timestamp = result.at("timestamp");
|
|||
|
|
EXPECT_TRUE(timestamp.length() == 19 || timestamp.length() == 20); // 考虑毫秒精度
|
|||
|
|
EXPECT_EQ(timestamp[4], '-');
|
|||
|
|
EXPECT_EQ(timestamp[7], '-');
|
|||
|
|
EXPECT_EQ(timestamp[10], ' ');
|
|||
|
|
EXPECT_EQ(timestamp[13], ':');
|
|||
|
|
EXPECT_EQ(timestamp[16], ':');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
TEST(HealthControllerTest, testHealthSpecialScenario) {
|
|||
|
|
HealthController controller;
|
|||
|
|
auto result1 = controller.health();
|
|||
|
|
auto result2 = controller.health();
|
|||
|
|
|
|||
|
|
// 确保两次调用返回的时间戳不同(非静态或缓存行为)
|
|||
|
|
EXPECT_NE(result1.at("timestamp"), result2.at("timestamp"));
|
|||
|
|
EXPECT_TRUE(result1.at("timestamp").length() > 0);
|
|||
|
|
EXPECT_TRUE(result2.at("timestamp").length() > 0);
|
|||
|
|
}
|