To fake a generic class, we will use the
Isolate.Fake.Instance API, and set the class name, for example:
Isolate.Fake.Instance<GenericClass<int>> ();
In this example, we will set a behavior of 3 methods: public, private and static.
public class GenericClass<T>
{
public string PublicMethod()
{
return " ";
}
private string PrivateMethod()
{
return " ";
}
public string CallPrivateMethod()
{
return this.PrivateMethod();
}
public static string StaticMethod()
{
return " ";
}
}
Public Method:
[TestMethod]
public void FakingPublicMethod()
{
var example = Isolate.Fake.Instance<GenericClass<int>>();
Isolate.WhenCalled(() => example.PublicMethod()).WillReturn("I'm a fake PublicMethod");
var expectedString = "I'm a fake PublicMethod";
var actualString = example.PublicMethod();
Assert.AreEqual(expectedString, actualString);
}
Private Method:
In order to fake a private method we will use the
isolate.NonPublic.WhenCalled API.
[TestMethod]
public void FakingPrivateMethod()
{
var example = new GenericClass<int>();
Isolate.NonPublic.WhenCalled(example, "PrivateMethod").WillReturn("I'm a fake PrivateMethod");
var expectedString = "I'm a fake PrivateMethod";
var actualString = example.CallPrivateMethod();
Assert.AreEqual(expectedString, actualString);
}
Static Method:
When faking a static method, we will use the
Isolate.Fake.StaticMethods API:
Isolate.Fake.StaticMethods<GenericClass<int>>().
to set a behavior on a ststic method (WhenCalled), we don't need an instance, just the name of the class.
[TestMethod]
public void FakingStaticMethod()
{
Isolate.Fake.StaticMethods<GenericClass<int>>(); //default for all static menthods
Isolate.WhenCalled(() => GenericClass<int>.StaticMethod()).CallOriginal();
var expectedString = "I'm in StaticMethod";
var actualString = GenericClass<int>.StaticMethod();
Assert.AreEqual(expectedString, actualString);
}