This action is invalid when the mock object is in verified state

I’ve long been noticing the following errors come up at the end of our NUnit testrun, but never had a chance to look into it in detail until now…They’ve never resulted in a broken build, and they do clearly look like something happening outside the scope of our unit test (even if it was caused by our test)

Unhandled exceptions:
1) : System.InvalidOperationException: This action is invalid when the mock object is in verified state.
at Rhino.Mocks.Impl.VerifiedMockState.MethodCall(IInvocation invocation, MethodInfo method, Object[] args)
at Rhino.Mocks.MockRepository.MethodCall(IInvocation invocation, Object proxy, MethodInfo method, Object[] args)
at Rhino.Mocks.Impl.RhinoInterceptor.Intercept(IInvocation invocation, Object[] args)
at ProxyInterfaceSystemSystemObject_System_DataIDataReader_Rhino_Mocks_InterfacesIMockedObject_System_Runtime_SerializationISerializable.Close()
at ExternalDataComponent.Data.DataRecordEnumerator.Dispose()
at ExternalDataComponent.Data.DataRecordEnumerator.Finalize()


Any obvious names have been masked to protect the innocent/stupid.

The error message quite is quite obvious in what the problem is, and leaves little doubt as to where it’s originating from….But the difficulty in this problem is finding out what causes the exception in the first place.

After attaching the VS debugger to NUnit, and turning on “Break On Exception” for the System.InvalidOperationException exception, All i would get is a debugger breaking into a location which was not relevant to any executing code, and the entire call stack consisted of non-managed code.

After a lot of thought, and with a little luck, i realised that what’s happening is that some of our tests are creating a stub object and passing it into the ExternalDataComponent during testing. The ExternalDataComponent is assuming that it is safe to call dispose on the object and thus doing so. The Rhino.Mocks framework then throws an exception when it intercepts the Dispose() method of the mocked interface, because the mock object “is in [the] verified state”.

My GoogleFu is in good form.

Unfortunately, we aren’t able to make changes to the ExternalDataComponent i’ve so eloquently disguised, as it’s a dependency library we’re using, so the “solution” is to reset all mocks to the original Record state before calling dispose (which additionally the tests weren’t doing).

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>