One of the new features that is part of the next release of StructureMap 2.5 is a AutoMocking Container.
What is an AutoMocking Container, well per Jacob over at Eleutian an AutoMocker is
AutoMockingContainer is simply a IoCContainer with a custom facility and dependency resolver that supplies a Mock (RhinoMock) for any interface that is resolved.
My definition is a little more straight forward and uses simpler word (remember I am a simpleton :))
An AutoMocking container is simply a tool that will inject mock dependencies into your object for you.
What I want to do today is show how an AutoMocking Container can reduce the amount of code/noise from your tests. I am going to first show a tests that simply uses RhinoMocks then that same test that uses the RhinoAutoMocker
Test with only RhinoMocks
[Test]
public void NoAutoMocker()
{
var mockProvider = MockRepository.GenerateMock<IPersistingRulesProvider>();
var mockRepository = MockRepository.GenerateMock<ISynchronizationRepository>();
var mockPersistanceProvider = MockRepository.GenerateMock<IPersistanceProvider>();
var mockLogger = MockRepository.GenerateMock<ILogger>();
// Expectations
mockProvider.Expect(x => x.ExecuteRules(null)).IgnoreArguments().Throw(new Exception("Do not care what this is"));
mockRepository.Expect(x => x.StartTransaction()).Repeat.Once();
mockRepository.Expect(x => x.RollbackTransaction()).Repeat.Once();
mockRepository.Expect( x => x.CommitTransaction() ).Repeat.Never();
var persitingPipeline = new PersistingPipeline(mockProvider, mockPersistanceProvider, mockRepository, mockLogger);
var result = persitingPipeline.PersistChanges(new DataSet(), 0, 0, 0);
Assert.That( result, Is.Not.Empty );
mockRepository.VerifyAllExpectations();
}
This code above has a bit of noise. Because my object has a dependency on 4 other objects i need to create mocks for each of these. This creates more work and just adds to the test noise.
Test with the RhinoAutoMocker
[Test]
public void WithAutoMocker()
{
var mockPipeline = new RhinoAutoMocker<PersistingPipeline>();
mockPipeline.Get<IPersistingRulesProvider>().Expect( x => x.ExecuteRules( null ) ).IgnoreArguments().Throw( new Exception( "Do not care what this is" ) );
mockPipeline.Get<ISynchronizationRepository>().Expect(x => x.StartTransaction()).Repeat.Once();
mockPipeline.Get<ISynchronizationRepository>().Expect(x => x.RollbackTransaction()).Repeat.Once();
mockPipeline.Get<ISynchronizationRepository>().Expect(x => x.CommitTransaction()).Repeat.Never();
var result = mockPipeline.ClassUnderTest.PersistChanges( new DataSet(), 0, 0, 0 );
Assert.That( result, Is.Not.Empty );
}
The code above does not require me to create mocks for each of my dependencies, the AutoMocker will do that for me.
Also notice that when I need to set an expectation for a dependencies I can access it via the .Get<>() method.
Till next time,
[----- Remember to check out DimeCasts.Net -----]
Posted
10-05-2008 1:58 PM
by
Derik Whittaker