How do I raise an event when a method is called using Moq?

后端 未结 3 709
被撕碎了的回忆
被撕碎了的回忆 2021-01-03 22:56

I\'ve got an interface like this:

public interface IMyInterface
{
    event EventHandler Triggered;
    void Trigger();
}

And I

3条回答
  •  無奈伤痛
    2021-01-03 23:49

    So I figured out what I was doing wrong. I'm going to post the answer here but give the credit to Nkosi because I didn't really ask the question correctly, and he provided a lot of useful information.

    With an async method on a mock, you need to first specify that it returns a Task before you can have it trigger events. So in my example (realizing that I should have had Task Trigger(); as the method signature, this is the code I was looking for:

    _mockedObject.Setup(i => i.Trigger())
        .Returns(Task.FromResult(default(object)))
        .Raise(i => i.Triggered += null, this, true);
    

    Apparently this can be simplified even further in C# 4.6, to this:

    _mockedObject.Setup(i => i.Trigger())
        .Returns(Task.CompletedTask)
        .Raise(i => i.Triggered += null, this, true);
    

提交回复
热议问题