Chris
Chris

Reputation: 1900

Shimming with Microsoft Fakes and a static, generic method

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<>()

Upvotes: 6

Views: 7939

Answers (1)

jessehouwing
jessehouwing

Reputation: 115017

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" });

Upvotes: 5

Related Questions