比较动作<t>

时间:2016-11-06 17:40:31

标签: c# tdd

我有一个服务类如下:

public class MyService
{
    private readonly IMyDependency _myDependency;

    public MyService(IMyDependency myDependency)
    {
       _myDependency = myDependency;
    }

    public void MyHandler(string param)
    {
       // work
    }

    public void AnotherMethod()
    {
       _myDependency.DoWork(MyHandler);
    }
}

如何单元测试MyHandler是否作为DoWork()的参数提供?

1 个答案:

答案 0 :(得分:1)

由于您使用的是Moq,您可以像这样编写测试:

[TestMethod]
public void DoWorkWasCalledWithCorrectParameters()
{
    var mock = new Moq.Mock<IMyDependency>();
    var myService = new MyService(mock.Object);
    myService.AnotherMethod();
    // verify that method was called once and with correct parameter:
    mock.Verify(x => x.DoWork(myService.MyHandler), Moq.Times.Once);
}