views:

325

answers:

1

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);
    }
+2  A: 

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);
Yacoder