Search code examples
unit-testingioxunitsimple-injector

Simple Injector and unit test?


We mainly use class injections theses days and that works great with unit test but there is some(a lot) of code that makes calls directly to the container and this results in problems while running tests.

In each test class I got a SetupData() method that will run once per class. This will add the data for this specific class test. This works fine as long as I do not run multiple (class) tests after each other. If I do that It will tell me that the container is locked.

private void SetupData()
{
    TestEntityviewCache evCache;
    if (!_dataIsSetup)
    {
        evCache = new TestEntityviewCache();
        IOC.Current.RegisterSingleton<IEntityViewCache>(evCache);

        EntityView.GetEntityViewListMethod = (key) => evCache.Get(key);
        EntityView.GetEntityViewListByIdMethod = (key) => evCache.Get(key);
    }
    evCache = IOC.Current.Get<TestEntityviewCache>();

    evCache.Update(EntityViewKey.Mappning, false, MyModelData.CreateMappning(), null);
    evCache.Update(EntityViewKey.Kontrakt, false, MyModelData.CreateKontrakt(), null);
    evCache.Update(EntityViewKey.Folder, false, MyModelData.CreateFolder(), null);
    evCache.Update(EntityViewKey.Kontaktgrupp, false, MyModelData.CreateKontaktGrupp(), null);
}

I have tried reseting or recreating the continer for each class test but I can´t find a solution?

The best solution would be to replace all direct IOC calls but that is to much work at this point.


Solution

  • In this case I hade to run the tests in sequence.