Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods Faking Asynchronous Methods

Faking Asynchronous Methods

You can fake async methods.

When to Use

When the method you wish to test is Asynchronous.

Syntax

C#

Isolate.WhenCalled(()=>ClassUnderTest.method()).WillReturn(Task.FromResult(return value));
var result = await ClassUnderTest.method();

VB

Isolate.WhenCalled(Function() ClassUnderTest.method()).WillReturn(Task.FromResult(return value))
Dim result = Await ClassUnderTest.method()

Sample 1: Faking the Result of an Asynchronous method

The following sample shows how to fake the result of an async method.

Method Under Test:
C#

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
}

VB

Public Async Function Login(model As LoginViewModel, returnUrl As String) As Task(Of ActionResult)
    Dim result = Await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout := False)
End Function

Test:
C#

var controller = new AccountController(); 
// Faking an async method, note that we are using Task.FromResult
Isolate.WhenCalled(() => controller.SignInManager.PasswordSignInAsync(null, null, true, true)).WillReturn(Task.FromResult(SignInStatus.Failure));
var result = await controller.Login(loginData, "http://www.typemock.com/");

VB

Dim controller = New AccountController()

' Faking an async method, note that we are using Task.FromResult
Isolate.WhenCalled(Function() controller.SignInManager.PasswordSignInAsync(Nothing, Nothing, True, True)).WillReturn(Task.FromResult(SignInStatus.Failure))

Dim result = Await controller.Login(loginData, "http://www.typemock.com/")