Using StructureMap with unit tests

Florim Maxhuni picture Florim Maxhuni · Feb 7, 2010 · Viewed 9k times · Source

I'm using StructureMap in a web project for DI IOC. It works perfect, but I don't have a clue how to write unit tests with StructureMap.

Should I do this in AssemblyInitialize start Configuration of StructureMap like in global.asax except for datacontext not to use live LinqToSqlDataContext but some memory data like this:

 [AssemblyInitialize]
 public static void Start()
 {
        ObjectFactory.Configure(x =>
                {
                    x.For<IDataContext>().HttpContextScoped().Use<MemoryDataContext>()
                        .Ctor<string>("connectionString")
                        .Is(ConfigurationManager.ConnectionStrings["DEVConnection"].ConnectionString);
                    x.For<IDepartamentRepository>().Use<DepartamentDB>();
                    x.For<IDevelopmentProcess>().Use<DevelopmentProcesses>().OnCreation(c => c.User = Current.CurrentUser);
                    x.For<IActivityProcess>().Use<ActivitiesProcess>().OnCreation(c=> c.User = Current.CurrentUser);
                    x.For<IDevDeveloperRepository>().Use<DevDeveloperDB>();
                    x.For<IDevelopmentRepository>().Use<DevelopmentDB>();
                    x.For<IActivityRepository>().Use<ActivityDB>();
                    x.For<IActivityTypeRepository>().Use<ActivityTypeDB>();
                    x.For<IDevUserRepository>().Use<DevUsersDB>();
                    x.For<IAttachmentRepository>().Use<AttachmentDB>();
                }
            );
 }

and then use ObjectFactory.GetInstance() testing or how do I do this?

Answer

Mark Seemann picture Mark Seemann · Feb 7, 2010

You shouldn't need to use a DI Container in unit tests at all.

A container is something you use to wire components together, but a unit test is a test of each component in isolation.