3

我正在寻找验证给定方法(单元)是否执行正确逻辑的最佳方法。

在这种情况下,我有一个类似于:

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

navigationService是接口的注入模拟版本,INavigationService. 现在,我想在我的单元测试中验证,它Navigate(...)是用正确的参数调用的。

但是,在 Windows Phone 上,IL 发射在一定程度上不受支持,其中模拟框架可以创建动态代理并分析调用。因此,我需要手动分析。

一个简单的解决方案是将Navigate(...)方法中调用的值保存在公共属性中,并在单元测试中检查它们。然而,对于所有不同类型的模拟和方法来说,这是相当烦人的。

所以我的问题是,有没有更聪明的方法来使用 C# 功能(例如委托)创建分析调用,而不使用基于反射的代理,并且不必手动保存调试信息?

4

1 回答 1

3

我的方法是手动创建 INavigationService 的可测试实现,该实现捕获调用和参数并允许您稍后验证它们。

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.
    }
}

然后可以在您的测试中使用它,例如:

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

    // Act
    classUnderTest.GoToMyPage();

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

我没有考虑传递给方法的参数,但我想这是一个好的开始。

于 2012-04-12T13:12:17.277 回答