26 October 2006

Rhinos mock objects exception

When creating a unit test, I got the following exception:

System.InvalidOperationException: "Can set only a single return value or exception to throw or delegate to throw on the same method call."


It appears that (1) you can't set multiple results from a function, obviously, and (2) the function has to be virtual.

I believe what Rhinos does is create a dynamic subclass of your class, then override the methods you want stubs for, using the behaviour you specify. This is why you can cast the resulting mock object to one of your classes and get the same results. If you don't have virtual methods... you're screwed.

What if you're mocking objects from a library and want to mock non-virtual methods?

If it's an object you want to mock:

If it's only for testing (and you have no control over the offending object), you can create an intermediary subclass in the test suite. In that class, create a new virtual method with the same stub, but different name. Fill in the method with a call to the original - since it's only used for testing, this will never be run, but if the API changes, the compiler will alert you.

If the object is returned from a library call, but you need to verify calls on it, you'll still need to create a proxy class, but it's going to have to be in your non-test code.

0 comments: