Rhino.Mocks ExpectationViolationException
Today, a colleague of mine Alex and me run into an exception thrown by Rhino.Mocks Framework by Ayande Rahien. How does it happen?
Let’s say that we have code like this.
1: [Test]
2: public void TestSomeMethod()
3: {
4: MockRepository mocks = new MockRepository();
5: IHelper helper = mocks.StrictMock<IHelper>();
6: IManager manager = new IManager(helper);
7: Expect.Call(helper.DoSomeWork("")).IgnoreArguments().Return(myObject);
8: mocks.ReplayAll();
9:
10: object result = manager.SomeMethod(); // here an exception of Rhino.Mocks.Exceptions.ExpectationViolationException has been thrown
11: Assert.IsTrue(result == null);
12: mocks.VerifyAll();
13: }
As you can see calling SomeMethod() we got an exception like
Rhino.Mocks.Exceptions.ExpectationViolationException: IHelper.DoSomeWork(""); Expected #1, Actual #2
Initially, we didn’t understand why such exception occurred because internally SomeMethod of IManager calls DoSomeWork of IHelper and this way all should be OK. Unfortunately, it wasn’t OK. Let me give a sample of how SomeMethod uses DoSomeWork.
1: public bool SomeMethod()
2: {
3: // some code here …
4: foreach(Person item in persons)
5: {
6: DoSomeWork(item.Firstname);
7: }
8: // some code here …
9: return result;
10: }
So, can you see the problem? Yes, the problem is that DoSomeWork can be called more than once. In order to tell Rhino.Mocks Framework that we have a method that we’d like to call more then once but at least once (what we need in our specific case) we need to change the expectations. below is the sample.
1: // old code - Expect.Call(helper.DoSomeWork("")).IgnoreArguments().Return(myObject);
2: Expect.Call(helper.DoSomeWork("")).IgnoreArguments().Repeat.AtleastOnce().Return(myObject); // new code
After instructing Rhino.Mocks that we will call DoSomeWork method more than once all get into its place.
Leave a Reply