Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Mocking JsonConvert.SerializeObject() in unit test using Moq and Autofixture

I am using Moq and Autofixture for creating a unit test for a method which processes a message containing an object and then serializes it. I am following dependency injection pattern to inject a bunch of objects to be used in the method. However, the method uses JsonConvert.SerializeObject() inside, and my tests fail at this spot. How do I mock the output of serialization?

public void A(MessageType message)
{
    ...
    // fails at this spot
    JsonConvert.SerializeObject(message.Result);
    ...
}

I've been told the reason behind this is that the tests do not go in SerializeObject() and this creates the error. For reference, I am using NewtonSoft.JSON.

Edit 1: I cannot change the method signature so we can't inherit JsonConvert and mock it and pass it to the method.

Edit : The error I get when I debug test is

Newtonsoft.Json.JsonSerializationException: 'Self referencing loop detected for property 'Object' with type 'Castle.Proxies.CategoryNodeProxy'. Path 'Mock'.'

Comments