Friday, March 4, 2011

Rhino Mocks - Setting up results for non-virtual methods

I'm playing around with Rhino Mocks and am trying to set some dummy results on my mocked objects so when they are called in my factory methods I don't have to worry about the data.

But I've hit a snag, the methods I want to have the dummy results for are causing exceptions because they aren't virtual.

I've got code like this:

using(mock.Record()){
  SetupResult.For(service.SomeMethod()).Return("hello world");
}

Does the SomeMethod method have to be a virtual to be have a mocked result?

Also, what's the difference between SetupResult.For and Expect.Call?

From stackoverflow
  • Rhino Mocks uses DynamicProxy2 to do it's magic, so you will not be able to set up expectations/results on non-virtual methods.

    As for the difference between SetupResult.For, and Expect.Call if you want your test to fail validation if a method is not called, use Expect.Call. If you just want to provide a result from your mock object, and you don't want to fail verification if it is not called, use SetupResult.For

    So the following will fail:

    using(mock.Record()){
        Expect.Call(service.SomeMethod()).Return("you have to run me");
    }
    
    using(mock.Replay()){
        // Some code that never calls service.SomeMethod()
    }
    

    And this test will not:

    using(mock.Record()){
        SetupResult.For(service.SomeMethod()).Return("you don't have to run me");
    }
    
    using(mock.Replay()) {
        // Some code that never calls service.SomeMethod()
    }
    

    Does that make sense?

    Slace : Thanks, that explains it well. I was compairing Typemock and Rhino Mocks when I found this. Typemock can mock non-virtuals so it's a plus in my book so far.
  • typemock isolator can do this: Typemock.com

    Slace : I know, but it's not free ;). But I do own a copy

0 comments:

Post a Comment