Search code examples
c++jsonunit-testinggoogletest

Writing a unit test in gtest for a function returning an nlohmann::json object


This is my function that I would like to create a test for:

static nlohmann::json parse_json(const std::string& file_path)
{
    std::ifstream i(file_path);
    nlohmann::json j = nlohmann::json::parse(i);
    return j;
}

I understand this type of test:

TEST(FactorialTest, HandlesZeroInput) {
  EXPECT_EQ(Factorial(0), 1);
}

But when my function is returning an object I'm not exactly sure how to accomplish this. Is this where mocking comes into play? Where I would need to write something like this:

class fakeJsonObject {
    public:
        MOCK_METHOD(nlohmann::json, parse_json, std::string& file_path);
};

Then create a test with my mocked object and compare it to an object created from my parse_json function?


Solution

  • General answer : a good unit test follow the rule AAA

    Arrange : place where you prepare things that will be tested

    Act : function call under test

    Assert : Assert that the function call gives you the right result.

    So in your case you have to prepare / or better generate a file containing json data. (Arrange).

    Call the function. (Act)

    Assert you got a nlhohmann::json object which is related to the json data contained in the file.(Assert)