在 googletest 中断言 JSON 格式的字符串等于

Assert JSON formatted string equals in googletest

我有一些功能要测试:

std::string getJsonResult(const SomeDataToProcessData& data);

目标是使用 googletest 框架用单元测试覆盖它。 我不能像字符串一样比较输出,因为相同的 JSON 可以有不同的格式。例如:

{"results":[], "status": 0}

对比

{
    "results":[], 
    "status": 0
}

我的这个问题的解决方案可作为 JUnit 的附加 library 使用,但我的项目是在 C++ 中。

如何使用 gtest 进行 JSON 格式化字符串断言?有已知的实现吗?

假设您有一些可用的 json_parsing/formatting 库,只需编写您自己的谓词即可:

#include <gtest/gtest.h>
#include <string>

// simulated JSON api
struct json_object {};
extern json_object parse(std::string json);
extern std::string format_lean(json_object const& jo);

testing::AssertionResult same_json(std::string const& l, std::string const& r)
{
    auto sl = format_lean(parse(l));
    auto sr = format_lean(parse(r));
    if (sl == sr)
    {
        return testing::AssertionSuccess();
    }
    else
    {
        return testing::AssertionFailure() << "expected:\n" << sl << "\n but got:\n" << sr;
    }
}

std::string make_some_json();

TEST(xxx, yyy)
{
    auto j_expected = std::string(R"__({ foo: [] })__");
    auto j_actual = make_some_json();

    ASSERT_TRUE(same_json(j_expected, j_actual));
}