public interface IServiceInvoker
{
R InvokeService<T, R>(Func<T, R> invokeHandler) where T : class;
}
public class MediaController : Controller
{
private IServiceInvoker _serviceInvoker;
public MediaController(IServiceInvoker serviceInvoker)
{
_serviceInvoker = serviceInvoker;
}
public JsonResult GetAllMedia()
{
var media = _serviceInvoker.InvokeService<IMediaService, List<MediaBase>>(proxy => proxy.GetAllMediaInJson());
JsonResult jsonResult = new JsonResult();
jsonResult.Data = media;
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jsonResult;
}
[TestClass]
public class MediaControllerTests
{
[TestMethod]
public void GetAllMedia()
{
JsonResult data;
var serviceInvoker = MockRepository.GenerateStub<IServiceInvoker>();
var media = CreateSeveralMedia();
serviceInvoker.Stub(c => c.InvokeService<IMediaService, List<MediaBase>>(p => p.GetAllMediaInJson())).Return(media);
data = new MediaController(serviceInvoker).GetAllMedia();
serviceInvoker.VerifyAllExpectations();
Assert.IsNotNull(data);
}
}
I am stubbing the service and returning a collection. When I run this test, media is null. Any idea, how can I set expectations on this mock ?
Just found a solution. It seems to be a little ugly, but it is the first iteration only probably more elegant version will appear soon. The idea is to create another stub and match
Func<>
against it: I will provide code for my use case:xUnit + extensions is used as testing framework. Please ignore
Theory
andInlineData
stuff -- it is just another way to get rid of unnecessary test setup.Here is the code of SUT:
Hope this will be helpful. Any suggestions of how to add more beauty are welcome :)
The lambda in your unit test compiles into a class-level method (a method inside your unit test). Inside your controller, a different lambda compiles into a class-level method (inside the controller). The stub set up in your unit test doesn't match the stub being executed in your controller, so Rhino Mocks returns a default (null). More here: http://groups.google.com/group/rhinomocks/browse_frm/thread/a33b165c16fc48ee?tvc=1