Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq. Execute Action given as a parameter

Tags:

c#

.net

action

moq

How to mock the following method:

public class TimeService : ITimeService
{
    public void SetDelyEvent(int interval, bool reset,  Action action)
    {
        var timer = new Timer {Interval = interval, AutoReset = reset};
        timer.Elapsed += (sender, args) => action();
        timer.Start();
    }
}

I want to call the given ACTION.

var stub = new Mock<ITimeService>();
stub .Setup(m => m.SetDelyEvent(100, false, ACTION));
like image 733
Miroslav Popov Avatar asked Sep 26 '14 21:09

Miroslav Popov


1 Answers

Just use the .Callback( method to invoke a method that will be run when your mock executes, your callback function can be passed in the Action that was passed in to your original method, all you need to do is execute the Action in your callback.

    var stub = new Mock<ITimeService>();
    stub .Setup(m => m.SetDelyEvent(It.IsAny<int>(), It.IsAny<bool>(), It.IsAny<Action>()))
         .Callback((int interval, bool reset, Action action) => action());
like image 87
Scott Chamberlain Avatar answered Oct 20 '22 14:10

Scott Chamberlain