Lironess
Lironess

Reputation: 843

Moq - setup mock to first-time callback and second-time raising an event

I got something looks like this :

public delegate void MyCallback(string name);

public class MyClass
{
    public virtual void MyFunc(string name, MyCallback callback)
    {
        ...
    }
}

Now, when I mock MyClass with moq, i would like the first call to MyFunc to call the callback, and the second call to that function to raise some event, but after the using moq callback i cannot raise an event !

What can I do ?

Upvotes: 4

Views: 5017

Answers (1)

k.m
k.m

Reputation: 31454

As far as I know, Moq doesn't support this kind of chaining, but you can easily make your ways around it:

var mock = new Mock<MyClass>();
int callsCount = 0;
mock
    .Setup(m => m.MyFunc(It.IsAny<int>(), It.IsAny<MyCallback>()))
    .Callback<int, MyCallback>(
        (i, callback) => 
        {
            if (callsCount++ == 0) callback("Some string");
            else mock.Raise(m => m.SomeEvent += null, EventArgs.Empty);
        });

Upvotes: 7

Related Questions