c# - 如何使用 Moq 和 NUnit 测试委托(delegate)

标签 c# delegates tdd moq func

我有一个工厂类返回如下委托(delegate)(GetDelegate 方法)

  public interface IFactory
{
    Func<int, string> GetDelegate(bool isValid);
}

public class AFactory : IFactory
{
    private readonly IService1 _service1;
    private readonly IService2 _service2;

    public AFactory(IService1 service1, IService2 service2)
    {
        _service1 = service1;
        _service2= service2;
    }

    public Func<int, string> GetDelegate(bool isValid)
    {
        if (isValid)
            return _service1.A;
        return _service2.B;
    }
}

public interface IService1
{
    string A(int id);
}

public interface IService2
{
    string B(int id);
}

我一直在尝试为 GetDelegate 编写单元测试,但不知道如何根据 isValid 断言返回了特定的 Func

我的单元测试尝试如下(我对此并不满意)

[Test]
    public void ShouldReturnCorrectMethod()
    {
        private var _sut = new AFactory(new Mock<IService1>(), new Mock<IService2>());

        var delegateObj = _sut.GetDelegate(true);
        Assert.AreEqual(typeof(string), delegateObj.Method.ReturnType);
        Assert.AreEqual(1, delegateObj.Method.GetParameters().Count());
    }

非常感谢任何帮助

谢谢

最佳答案

一种方法是模拟调用 IService1.AIService2.B 的结果,就像您直接调用它们一样。然后,您可以检查当您调用返回的委托(delegate)时,您是否得到了预期的答案(并且调用是对适当的服务进行的)。

关于c# - 如何使用 Moq 和 NUnit 测试委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31189565/

相关文章:

java - 如何在 Spring Boot 应用程序中测试 native 查询?

c# - _NAME、__NAME、_NAME_、__NAME__ 等符号的含义

ios - self.delegate 总是 nil

c# - Simple Delegate(委托(delegate))与多播委托(delegate)

c# - C# 中的 lambda 创建的委托(delegate)的生命周期是多少?

c# - 当返回类型为 ActionResult 时,如何对操作进行单元测试?

javascript - react 如何测试在 FileReader onload 函数中调用的函数

c# - 为什么在我的 Web API (ASP.NET v5) 项目中添加依赖项无法完全正常工作?

c# - 动态 Linq.Table<TEntity> 可能吗?

c# - 带有文化的 MVC5 本地化 - 拥有区域的问题