Faking Extension Methods
Extension methods enable you to extend other classes with methods of your own. Extension methods cannot access private or protected members of the extended class. The extension class is a static class (which means all methods and fields are static).
When to Use
When your test requires a specific return value from an extension method.
Faking Instance.Extension is equivalent to faking Type.Extension static method.
Syntax
C# Isolate.WhenCalled(() => myObject.<extension>()).<behavior>;
VB
Isolate.WhenCalled(Function() => myObject.<extension>()).<behavior>
Samples
The following sample shows how to fake the DoubleInt() method. After faking the method, it will return 100 instead of 2.
C# [TestMethod, Isolated] public void TestExtensionMethods() { Isolate.WhenCalled(() => 1.DoubleInt()).WillReturn(100); int n = 1; Assert.AreEqual(100, n.DoubleInt()); } public static class Foo { public static int DoubleInt(this int n) { return 2 * n; } }
VB
<TestMethod, Isolated>
Public Sub TestExtensionMethods()
Isolate.WhenCalled(Function() 1.DoubleInt()).WillReturn(100)
Dim n As Integer = 1
Assert.AreEqual(100, n.DoubleInt())
End Sub
Public Module Module1
Sub Main()
End Sub
<Extension()>
Public Function DoubleInt(ByRef n As Integer) As Integer
Return 2 * n
End Function
End Module