Using StructureMap with unit tests

后端 未结 2 1045
北海茫月
北海茫月 2021-01-11 18:24

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 Assemb

相关标签:
2条回答
  • 2021-01-11 18:46

    I agree with Mark. Testability is one of the primary reasons you are likely using a container in the first place.

    There are times where creating an integration test for your container setup might be a good idea. For example if you have any behavior in your container configuration you will want to create tests for that behavior. In you container config you set IDataContext's connection string via the configuration manager.

    The following code is similar to what I do to test such a setup. Notice I avoid ObjectFactory (static singleton objects have their own problems) and wrap my container setup in a bootstrapper helper class:

    [Test]
    public void connection_string_should_come_from_application_configuration()
    {
      var container = new ContainerBootstraper().Container;
    
      var connectionString = container.GetInstance<IDataContext>().ConnectionString
    
      connectionString.ShouldEqual("test project application configuration connection string");
    }
    
    0 讨论(0)
  • 2021-01-11 19:03

    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.

    0 讨论(0)
提交回复
热议问题