Tencent / rapidjson

A fast JSON parser/generator for C++ with both SAX/DOM style API
http://rapidjson.org/
Other
14.17k stars 3.52k forks source link

How to mock GenericValue using gtest/gmock. #1232

Open princrai opened 6 years ago

princrai commented 6 years ago

I have something namespace abc { namespace json { typedef rapidjson::GenericValue<rapidjson::UTF8<> > Value; } // ns json } // ns abc

and void Serialize(const string& filename, const abc::json::Value& json) const { // here I serialize json to a file using FileWriterStream. and use rapidjson::Writer writer(os); bool written = json.Accept(writer).

if(written)
       // do something
else
         // do else.

}

I am writing some unit test for this function, where I want to return false from json.Accept(writer) . One option is by mocking json class which is GenericValue class in the library itself. Or the simple option can be creating writer in such a way that it can json.Accept can return false. Or maybe creating the json Value such that it's incomplete/partial json object.

Can you let me know how can I achieve to make json.Accept to return false. Maybe a example will be more helpful .

Thanks, Prince

miloyip commented 6 years ago

Setting a value with inf or nan can make the writer returns false, and then making Accept() to return false. It is because the JSON standard does not permit this.

static double zero = 0.0;

Document d;
d.SetDouble(zero / zero); // NaN
assert(d.Accept(...) == false);
Bu11etmagnet commented 6 years ago

In general, gmock relies on virtual functions to replace functionality. FileWriterStream methods are not virtual, mocking it is going to be difficult. Also, your Serialize method creates a FileWriterStream object. This means that Serialize can never use a mocked FileWriterStream. If you want to replace a "real" object with a mock, you need to pass the object as a parameter to the function. Then the real code can give a real object and test code can give a mock object to the function under test. This is called dependency injection.