如何使用Moq和NUnit测试委托

时间:2015-07-02 16:08:32

标签: c# delegates tdd moq func

我有一个工厂类返回如下所示的委托(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());
    }

非常感谢任何帮助

感谢

2 个答案:

答案 0 :(得分:2)

一种方法是模拟调用IService1.AIService2.B的结果,方式与您直接调用它们的方式完全相同。然后,您可以检查当您调用返回的委托时,您会得到预期的答案(并且调用了相应的服务)。

答案 1 :(得分:1)

[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);
}