ServiceLocator can't be reset during unit testing

Vote:
 

Hi all

I'm mocki  gup the ServiceLocator for unit tests but it seems like it can't reset during a batch of tests. Typical code i'm using is

            IServiceLocator serviceLocator = MockRepository.GenerateMock<IServiceLocator>();
            var mockRepository = MockRepository.GenerateMock<IContentRepository>();

            mockRepository.Stub(x => x.GetChildren<FilterFolder>(Arg<ContentReference>.Is.Anything)).Return(new List<FilterFolder> { new FilterFolder() });
            mockRepository.Stub(x => x.GetChildren<FilterComponent>(Arg<ContentReference>.Is.Anything)).Return(new List<FilterComponent> { new FilterComponent() });

            serviceLocator.Stub(x => x.GetInstance<IContentRepository>()).Return(mockRepository);
            ServiceLocator.SetLocator(serviceLocator);

The scenario is

I have a particular test that I want to set the IContentRepository differently. So I write the above code in - the other tests call a setup routine which sets service locator with some defaults

So

1. I run all tests - they one with the custom locator setup fails

2, I run just the failing one - still fails

3. I add whitespace to the failing project - recompile and it magically starts to work (it seems to have picked up the correct Service Locator)

4. I rerun all the test - about 20 of them fail now (they are using the wrong locator although the code has set it up correctly)

It sems as it when setting up the locator in a batch of tests it is first one wins. It can't be overriden during a bacth of tests.

I jknow this is all a bit weird but has anyone come across this. It seems like my unit tets are suddenly not isolated which isn't good.

Many Thanks for any all help

Tim B

 

 

 

 

 

 

#79349
Dec 13, 2013 15:38
Vote:
 

Hi all - just to simplify this post. Basically the mocks setup with ServiceLocator.SetLocator(serviceLocator); can't be replaced in subsequent unit tests. So at the moment i can only setup one set of IContentRepositories etc.. I would like to set up different return values in different tests. Looks like EPisServer is caching the locator.

Does that make any more sense?

Cheers

#79440
Dec 17, 2013 13:41
Vote:
 

Hi Tim - Old post but unanswered, I think 

ServiceLocator.SetLocator(null);

does the trick.  Replacing stub methods on the existing instance also seems to work.

#88773
Jul 30, 2014 12:14
This thread is locked and should be used for reference only. Please use the Episerver CMS 7 and earlier versions forum to open new discussions.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.