Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 835
Lironess Avatar asked Sep 11 '25 12:09

Lironess


1 Answers

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);
        });
like image 135
k.m Avatar answered Sep 14 '25 01:09

k.m