Dynamic Return Value and Mock Abuse

Oren (Ayende) wrote about mock abuse. In his example an entire behavior is substituted using the mocking framework. It’s a really good example for what not to do.

How is it done? Note the Do segment of the call:

stubbedIncomingMessageRepository
.Stub(x => x.GetEarliestMessage())
.Return(null)
.Do(invocation =>
{
lock (msgQueue)
{
invocation.ReturnValue = msgQueue.Count == 0 ? null : msgQueue.Dequeue();
}
})
.Repeat.Any();

It replaces the original method with another implementation, which is invoked when the original method is called.

The equivalent in Typemock Isolator is called “Dynamic return values”. It allows you to perform any implementation instead of an original one, and return a value based on that implementation.

It’s very powerful. You can do magic with it. But don’t abuse it. Keep your tests simple and readable.

TOP