Claus Jørgensen
Claus Jørgensen

Reputation: 26344

Verify method call and parameters without a mocking framework

I'm looking for the best way to verify that a given method (the unit) is executing the correct logic.

In this case, I have a method similar to:

public void GoToMyPage()
{
    DispatcherHelper.BeginInvoke(() =>
    {
        navigationService.Navigate("mypage.xaml", "id", id);
    });
}

The navigationService is a injected mocked version of a interface, INavigationService. Now, I want to verify in my unit tests, that Navigate(...) is called with the correct parameters.

However, on Windows Phone IL emitting is not supported to a degree, where a mocking framework can create a dynamic proxy, and analyze the call. Therefor I need to analyze this manually.

A simple solution would be to save the values called in the Navigate(...) method in public properties, and check them in the unit tests. However, this is rather tiresome having to do for all different kinds of mocks and methods.

So my question is, is there a smarter way to create analyze calls using C# features (such as delegates), without using a reflection based proxy, and without having to saving the debug info manually?

Upvotes: 3

Views: 3045

Answers (1)

gbanfill
gbanfill

Reputation: 2216

My approach would be to manually create a testable implementation of the INavigationService that catches the calls and parameters and allows you to verify them later.

public class TestableNavigationService : INavigationService
{
    Dictionary<string, Parameters> Calls = new Dictionary<string, Parameters>();

    public void Navigate(string page, string parameterName, string parameterValue)
    {
        Calls.Add("Navigate" new Parameters()); // Parameters will need to catch the parameters that were passed to this method some how
    }

    public void Verify(string methodName, Parameters methodParameters)
    {
        ASsert.IsTrue(Calls.ContainsKey(methodName));
        // TODO: Verify the parameters are called correctly.
    }
}

this could then be used in your test something like:

public void Test()
{
    // Arrange
    TestableNavigationService testableService = new TestableNavigationService ();
    var classUnderTest = new TestClass(testableService );

    // Act
    classUnderTest.GoToMyPage();

    // Assert
    testableService.Verify("Navigate");
}

I havent thought about the Parameters that are passed into the method, but I guess this is a good start.

Upvotes: 3

Related Questions