Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq'ing the raising of events multiple times

In a particular unit test I'm trying to raise an event multiple times and then to veryify a property value after the final event has been raised. I have something like

public void TurnRight()
{
   var mockFoo = new Mock<IFoo>();

   SomeService someService= new SomeService ();
   someService.Foo= mockFoo.Object;

   mockFoo.Raise(foo=> foo.TurnedRight += null, EventArgs.Empty);
   mockFoo.Raise(foo=> foo.TurnedRight += null, EventArgs.Empty);
   mockFoo.Raise(foo=> foo.TurnedRight += null, EventArgs.Empty);

   mockFoo.VerifySet(foo=> foo.Orientation = Orientation.West);
}

Orientation actually only changed to east (as I believe the event is only getting raised once). Am I doing something wrong? This is the first time i've used moq so I'm probably missing something.

Cheers J

edit... the correct code i should have been using

public void TurnRight()
    {
       var mockFoo = new Mock<IFoo>();

       SomeService someService= new SomeService ();
       someService.Foo= mockFoo.Object;

       mockFoo.SetupProperty(foo=> foo.Orientation);

       mockFoo.Raise(foo=> foo.TurnedRight += null, EventArgs.Empty);
       mockFoo.Raise(foo=> foo.TurnedRight += null, EventArgs.Empty);
       mockFoo.Raise(foo=> foo.TurnedRight += null, EventArgs.Empty);

       Assert.AreEqual(mockFoo.Object.Orientation, Orientation.South);
    }
like image 200
James Hay Avatar asked Dec 01 '09 14:12

James Hay


1 Answers

mockFoo.Raise should be fine, raising the event three times... Can you put a breakpoint in the event handler and check how many times is it called?

Another potential mistake here as I can see, is that you should first tell Moq to start tracking all sets/gets of a property before you can verify it (and before you raise the events):

// start "tracking" sets/gets to this property
mockFoo.SetupProperty(foo=> foo.Orientation);
like image 115
Max Galkin Avatar answered Sep 18 '22 13:09

Max Galkin