Question

I need to shim a static generic method for a unit test. However, I can't seem to get Fakes to create the shim object. Does anyone know how to accomplish this?

In particular, I want to shim Newtonsoft's JsonConvert.DeserializeObject<>()

Was it helpful?

Solution

For each return type that you would expect register a delegate like so:

With this code in the Unit Test:

using (var context = ShimsContext.Create())
{
    ShimJsonConvert.DeserializeObjectOf1String<SomeJSonObject>(s => new SomeJSonObject() { Name = "Foo" });

    SomeJSonObject o = ConsoleApplication3.Program.Deserialize();
    Assert.IsNotNull(o);
    Assert.AreSame(o.Name, "Foo");
}

And this code under test:

return JsonConvert.DeserializeObject<SomeJSonObject>("");

It works as expected for me.

If needed also register the other overloads. So if you're using some of the other overloads, you must also register their corresponding delegates on the Shim:

Other Overloads

Like:

ShimJsonConvert.DeserializeObjectOf1String<SomeJSonObject>(s => new SomeJSonObject() { Name = "Foo" });
ShimJsonConvert.DeserializeObjectOf1StringJsonConverterArray((s, convertors) => new SomeJSonObject() {Name = "Bar"});
ShimJsonConvert.DeserializeObjectOf1StringJsonSerializerSettings((s, settings) => new SomeJSonObject() { Name = "Bar" });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top