While writing some code today I thought I would give Moq a shot in place of RhinoMocks. One thing I was very happy about was that I found it very easy to pickup, which is a plus.
However, I did want to mention one small gotcha I ran into. I was trying to inject a mock into StructureMap via the ObjectFactory.InjectStub() like i have done numerous times in the past. However this time i received the following SM error.
StructureMap.StructureMapException: StructureMap Exception Code: 220
Cannot "Stub" type ......Repositories.ITrackingRepository with an object of type Moq.Mock`1
The good news is this error is real easy to overcome. Below you will find the 'breaking code' along with the 'working code'
Breaking Code
public void TrackEpisodeDetailsView_ExpectCallToRepository()
{
var mockTrackingRepository = new Mock();
mockTrackingRepository.Expect( x => x.LogEpisodeDetailsView( It.IsAny(), It.IsAny() ) ).Returns( new TrackingEpisodeView() );
ObjectFactory.InjectStub( typeof(ITrackingRepository), mockTrackingRepository );
var tracking = new Tracking();
tracking.TrackEpisodeDetailsView( 1, "" );
}
Working Code
public void TrackEpisodeDetailsView_ExpectCallToRepository()
{
var mockTrackingRepository = new Mock();
mockTrackingRepository.Expect( x => x.LogEpisodeDetailsView( It.IsAny(), It.IsAny() ) ).Returns( new TrackingEpisodeView() );
ObjectFactory.InjectStub( typeof(ITrackingRepository), mockTrackingRepository.Object );
var tracking = new Tracking();
tracking.TrackEpisodeDetailsView( 1, "" );
}
You will notice the one slight change. When passing the mock into the InjectStub method you need to use the mock.Object property to actually return the mock instance, not the Moq wrapper.
Till next time,
Posted
05-11-2008 11:07 AM
by
Derik Whittaker