Skip to content

Usage with gtest/gmock not working as expected #1044

@deblauwetom

Description

@deblauwetom

I am trying to use the library with google test/google mock. It seems gtest is not able to print the json value out with its universal printer.

Example that fails:

#include <gtest/gtest.h>
#include <nlohmann/json.hpp>

using json = nlohmann::json;
using namespace testing;

TEST(EnsureJsonComparesCorrectly)
{
   auto test1 = R"BLA(
{
    "event" : "test",
    "description" : "Test description"
}
)BLA"_json;

   auto test2 = R"BLA(
{
    "description" : "Test description",
    "event" : "test"
}
)BLA"_json;
    EXPECT_THAT(test1, Eq(test2));
}

I am using 3.1.2 of nlohmann and 1.8.0 of google test/mock. I am compiling and running on macOS.

I also tried to use it with gmock, but it also fails. The myCall function is defined as:

void myCall(std::string url, nlohmann::json message);

So this is in gmock:

MOCK_METHOD2(myCall, void(std::string url, nlohmann::json message));

And then in the test I set an expectation, like this:

 EXPECT_CALL(*myMock, myCall(_, test1));

but every time gtest tries to print, in this case the "test1" object, then it crashes.

So what could causing this? Gtest is normally able to use a custom PrintTo function but I could not get that to work. Any pointers on how to solve it?

I have a "workaround" but it goes against the "json as first-class citizen" philosophy :)
Workaround for EXPECT_THAT:

EXPECT_THAT(test1.dump(), Eq(test2.dump()));

That is more or less acceptable, but not really.
And then for gmock it is really too much :) see:

json tmp;
json test;
EXPECT_CALL(*myMock, myCall(_, _)).WillOnce(SaveArg<1>(&tmp));
EXPECT_THAT(tmp.dump(), Eq(test.dump()));

But of course it should be as easy as:

EXPECT_CALL(*myMock, myCall(_, test));

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions