Take the 2-minute tour ×

Suppose I have a strongly typed caching interface that I want to mock. It takes objects of any kind and returns them, like this:

interface IMyCache
   void Add( int key, object obj );
   T Get<T>(int key);

Can I write a RhinoMocks stub that will mock any parameter type that I send to it? Ideally it would just look something like this:

var mock = MockRepository.GenerateStub<IMyCache>();
mock.Stub( m => m.Get<T>(1234)).Return( new T());

This doesn't work because it's expecting T to be a concrete class, but I'd like to genericize it. Is this possible?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

I don't think you can. When writing tests with rhino mocks, you need to follow the rules of the compiler, and avoiding to specify the generic type T, makes the compiler unhappy.

If you need to reuse that stub-code between multiple tests, each using different types for T, you can make a helper method as proposed here: Rhino Mocks: How to stub a generic method to catch an anonymous type?

share|improve this answer
add comment

Your Answer


