Someone asked for examples of how you'd inject stubs and mocks when you'd like your object under test to use a container such as StructureMap.
here are a couple of simple tests to show this using Typemock Isolator.
the first uses the string based mocks found in the free community version of Typemock Isolator. the second uses the natural style syntax in the enterprise edition:
- assume you have ILogger, IEmailer interfaces and a MessageManager class under test that takes both of these in the ctor.
- The logic under test is: if calling the emailer throws an exception, the logger should be called with the message that was sent
[Test, VerifyMocks]
public void MessageManager_FailsEmailing_LogsMessage_ReflectiveStructureMap()
{
StructureMapConfiguration.BuildInstancesOf<IEmailer>().AddConcreteType<Emailer>();
StructureMapConfiguration.BuildInstancesOf<ILogger>().AddConcreteType<Logger>();
MockObject<IEmailer> emailStub = MockManager.MockObject<IEmailer>();
emailStub.AlwaysThrow("Send", new Exception("fake exception"));
MockObject<ILogger> logMock = MockManager.MockObject<ILogger>();
logMock.ExpectCall("Write").Args("could not email message abc");
ObjectFactory.InjectStub(emailStub.MockedInstance);
ObjectFactory.Inject(logMock.MockedInstance);
MessageManager mm = ObjectFactory.GetInstance<MessageManager>();
mm.SendMessage("abc");
}
----------------------------------------
[Test, VerifyMocks]
public void MessageManager_FailsEmailing_LogsMessage_NaturalStructureMap()
{
StructureMapConfiguration.BuildInstancesOf<IEmailer>().AddConcreteType<Emailer>();
StructureMapConfiguration.BuildInstancesOf<ILogger>().AddConcreteType<Logger>();
IEmailer emailStub = RecorderManager.CreateMockedObject<IEmailer>();
ILogger logMock = RecorderManager.CreateMockedObject<ILogger>();
using (RecordExpectations re = RecorderManager.StartRecording())
{
emailStub.Send("", "", "", "");
re.Throw(new Exception("fake exception")).RepeatAlways();
logMock.Write("could not email message abc");
}
ObjectFactory.InjectStub(emailStub);
ObjectFactory.Inject(logMock);
MessageManager mm = ObjectFactory.GetInstance<MessageManager>();
mm.SendMessage("abc");
}