Faking Local Functions
You can control local functions by doing the following:
• Faking private local functions.
• Faking private static local functions
When to Use
When your test requires a specific return value from faked local function.
Public methods are also supported with Isolate.NonPublic. This enables you to change the visibility of your methods without changing your tests.
Faking Local Functions
To fake local functions, use the Isolate.NonPublic. This API uses a string name of the method that you want to fake. Typemock Isolator will find the method through reflection and arrange the new behavior. To fake an instance method, pass the instance and the name of the method.
To allow
production code to change its method scope without failing unit tests, Isolate.NonPublic can be
used for public methods too.
Syntax
C# Instance: Isolate.NonPublic.WhenCalledLocal(<instance>, "<methodname>", "<localfunctionname>").<behavior> Static: Isolate.NonPublic.WhenCalledLocal<type>("<methodname>", "<localfunctionname>").<behavior>
The following table explains possible behavior:
Behavior |
Description |
WillReturn |
Returns a specified value. |
WillThrow |
An exception will be thrown when this method will be called. |
IgnoreCall |
The method will not be executed. |
CallOriginal |
Calls the original method. |
DoInstead |
Calls a user code. This option is used for advanced and complex behaviors. |
Sample 1: Changing behavior of local function under instance method
C# var fake = Isolate.Fake.Instance<ClassWithLocal>(Members.CallOriginal); Isolate.NonPublic.WhenCalledLocal(fake, "UseIntLocal", "GetLocal").WillReturn(3);
Sample 2: Changing behavior of local function under static method
C# Isolate.NonPublic.WhenCalledLocal<ClassWithStaticLocal>("UseStaticLocal", "GetLocal").WillReturn(3);
Sample 3: Returning different value
To set a different behavior to a local function, which returns 5, use WillReturn() with a different value.
C# [TestMethod] public void FakeLocalFunctionReturningDifferentNumber() { var instance = new ClassUnderTest(); Isolate.NonPublic.WhenCalledLocal(instance, "IsGreaterThan10", "GetLocal").WillReturn(20); var result = instance.IsGreaterThan10(); Assert.IsTrue(result); } public class ClassUnderTest { public bool IsGreaterThan10() { int GetLocal() { return 5; } var value = GetLocal(); if (value > 10) return true; return false; } }