In a previous post I talked about how you can setup StructureMap to create and use profiles. In this post I would to show you how you can swap out an instance of an object which is part of the profile with a fake/stub for testing.
I ran into this scenario the other day while creating a test and I needed to inject a mock into the ObjectFactory. If you are not using profiles this is pretty straight forward, you simple do the following
ObjectFactory.Inject( someobjecttoinjectgoeshere);
However, when you are working with profiles this does not work (per Jeremy it may be a bug, but he is not 100% sure and I spent 30-60 minutes walking through SM code and could not determine whether it was or not). In order to replace a instance which was going to be built based on the current profile you need to do the following.
ObjectFactory.Configure( x => {
x.CreateProfile( “ProfileName”,
z => { z.For<ITypeeToUse>().Use( mockObjectToInject ); }
} );
If you use the code example above you should be able to tell the ObjectFactory to use your mock rather than an actual instance. But be careful, this mock will remain until the profile is destroyed or you reset the object factory.
Hope this helps.
Till next time,
Posted
01-09-2009 7:52 PM
by
Derik Whittaker