如何使用 Moq 和 NUnit 测试委托

How to test a delegate using Moq and NUnit

我有一个工厂 class 返回如下委托(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 的结果,就像直接调用它们一样。然后您可以检查当您调用返回的委托时,您是否得到了预期的答案(并且调用是对适当的服务进行的)。

[Test]
public void GetDelegate_WhenCalledWithIsValidTrue_ReturnsDelegateA()
{
    // Arrange
    Mock<IService1> service1Mock = new Mock<IService1>();
    Mock<IService2> service2Mock = new Mock<IService2>();

    string expectedResultA = "A";
    string expectedResultB = "B";

    service1Mock.Setup(s => s.A(It.IsAny<int>())).Returns(expectedResultA);
    service2Mock.Setup(s => s.B(It.IsAny<int>())).Returns(expectedResultB);

    var _sut = new AFactory(service1Mock.Object, service2Mock.Object);

    // Act
    Func<int, string> delegateObj = _sut.GetDelegate(true);

    // Assert
    string result = delegateObj(0);
    Assert.AreEqual<string>(expectedResultA, result);
}