Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I've got an interface like this:

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

And I've got a mocked object in my unit test like this:

private Mock<IMyInterface> _mockedObject = new Mock<IMyInterface>(); 

I want to do something like this:

// pseudo-code _mockedObject.Setup(i => i.Trigger()).Raise(i => i.Triggered += null, this, true); 

However it doesn't look like Raise is available on the ISetup interface that gets returned. How do I do this?

like image 295
soapergem Avatar asked May 17 '16 21:05

soapergem


People also ask

What can be mocked with Moq?

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces.

Can you mock a private method Moq?

Moq supports mocking protected methods. Changing the methods to protected , instead of private , would allow you to mock their implementation.

What is Moq mocking framework?

Moq is a mocking framework built to facilitate the testing of components with dependencies. As shown earlier, dealing with dependencies could be cumbersome because it requires the creation of test doubles like fakes. Moq makes the creation of fakes redundant by using dynamically generated types.

Is Moq a testing framework?

The Moq framework is an open source unit testing framework that works very well with . NET code and Phil shows us how to use it.


1 Answers

Your pseudo-code was almost spot on. You needed to use Raises instead of Raise. Check the Moq Quickstart: Events for versions Moq 4.x and you will see where you made the mistake.

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

Here is the snippet form GitHub

// Raising an event on the mock mock.Raise(m => m.FooEvent += null, new FooEventArgs(fooValue));  // Raising an event on a descendant down the hierarchy mock.Raise(m => m.Child.First.FooEvent += null, new FooEventArgs(fooValue));  // Causing an event to raise automatically when Submit is invoked mock.Setup(foo => foo.Submit()).Raises(f => f.Sent += null, EventArgs.Empty); // The raised event would trigger behavior on the object under test, which  // you would make assertions about later (how its state changed as a consequence, typically)  // Raising a custom event which does not adhere to the EventHandler pattern public delegate void MyEventHandler(int i, bool b); public interface IFoo {   event MyEventHandler MyEvent;  }  var mock = new Mock<IFoo>(); ... // Raise passing the custom arguments expected by the event delegate mock.Raise(foo => foo.MyEvent += null, 25, true); 
like image 98
Nkosi Avatar answered Sep 30 '22 20:09

Nkosi