在没有模拟框架的情况下验证方法调用和参数

本文关键字:方法 验证 调用 参数 情况下 模拟 框架 | 更新日期: 2023-09-27 18:31:05

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

在这种情况下,我有一个类似于以下方法的方法:

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

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

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

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

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

在没有模拟框架的情况下验证方法调用和参数

我的方法是手动创建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");
}

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