tags:

views:

47

answers:

1

Is there a way to create a mock object based on an already existing object? For example, when unit testing ASP.NET MVC applications, I often run into the problem of mocking repository methods (like GetAll). Usually I want to get this method to return some test data, like this:

    private List<Country> CreateCountries()
    {
        return new List<Country> { 
                                new Country("Australia", "AU", "AUS"),
                                new Country("Canada", "CA", "CAN"),
                                ...
                                 };
    }

My entity objects all derive from a PersistedEntity base class which has an Id property, but it can only be set by NHibernate, so when I create these objects from scratch they have Id = 0. This is problematic for unit tests since they give controllers unrealistic entity lists that have all their Id's set to 0.

I'd really like to be able to set the IDs on these objects by doing something like

new Country("United States", "US", "USA").SetID<Country>(3); *

Where SetID would be an extension method on PersistedEntity:

    public static T SetID<T>(this T entity, int id) where T : PersistedEntity
    {
        var mocks = Mocker.Current;

        // Some kind of magic happens here that creates a mocked version of
        // entity (entity2), which has the same values as the original entity
        // object but allows us to set up new expectations on it like...

        Expect.Call(entity2.Id).Return(id);

        return entity2;
    }

Anyone know if there's some magic like that in Rhino Mocks?

* I suspect that it will be necessary to make this method generic, but if not, even better.

+1  A: 

If I have understood your problem correctly, you should be able to do it like the following:

var country = MockRepository.GenerateMock<Country>("Australia", "AU", "AUS");

...

country.Stub(c => c.Id).return(5); // whatever arbitrary id you want to give it

...

return new List<Country> { country, ... };

I've assumed here that Country is not sealed i.e. so RhinoMocks is able to generate a mock of that class.

jpoh