Cedric Royer-Bertrand Cedric Royer-Bertrand - 1 month ago 8
C# Question

Compare Action<T>

I have a service class as below:

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


How can I Unit Test that MyHandler has been given as a parameter of DoWork()?

Answer

Since you are using Moq, you can write test like this:

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