taarraas taarraas - 1 year ago 96
JSON Question

Assert JSON formatted string equals in googletest

I have some function to test:

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

The goal is to cover it with unit tests using googletest framework.
I can't compare output just as strings, because there can be different formatting for the same JSON. E.g.:

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


"status": 0

The solution for my this issue is available as additional library for JUnit, but my project is in C++.

How to do JSON formatted string assertion using gtest? Are there known implementations?

Answer Source

assuming you have some json_parsing/formatting library available, it's simply a matter of writing your own predicate:

#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();
        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));