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

后端 未结 3 691
被撕碎了的回忆
被撕碎了的回忆 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:53

    Expanding on SoaperGEM's answer, all methods that return something (no matter the type) must have that return value specified before triggering the event. Since async methods return Task, async methods fall into this category. I have a method that returns a string, and I was trying to figure out why I couldn't trigger the event with the Mock object. Then I tried returning first and it worked just fine.

    Taking SoaperGEM's example, and assuming Trigger() returns a string:

    _mockedObject.Setup(i => i.Trigger())
        .Returns("somestring")
        .Raises(i => i.Triggered += null, this, true);
    

提交回复
热议问题