Yesterday I found myself stucked with a strange exception while programming a unit test using Rhino Mocks.

Supose you have an interface like the following one.

1
2
3
4
public interface ITest
{
    object Freak();}

You can try a mock like the following:

1
2
3
4
5
var test = MockRepository.GenerateMock();
 
test.Expect(t => t.Freak()).IgnoreArguments()    .WhenCalled(x => x.ReturnValue = "THIS IS A RETURN VALUE")
    .Repeat.Any();

Calling test.Freak(); will result in a return value of “THIS IS A RETURN VALUE”

Now change the interface to be:

1
2
3
4
public interface ITest
{
    string Freak();}

Calling test.Freak(); results in the following exception: Method ‘ITest.Freak();’ requires a return value or an exception to throw.

The solution is easy just change the Expect call to look like this one:

1
2
3
4
test.Expect(t => t.Freak()).IgnoreArguments()
    .WhenCalled(x => x.ReturnValue = "THIS IS A RETURN VALUE")
    .Return(string.Empty) // THIS IS NEEDED SO RHINO MOCKS KNOWS THE TYPE RETURNED FROM THE METHOD CALL.    .Repeat.Any();

The fake return value is ignored in favor of the given by the WhenCalled delegate!!!

Hope it helps.

Leave a Reply

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