Unit tests

I have a singleton that contains a link to a statistics object.

When I run a couple test unit in a program that uses this singleton, the values ​​are supported between tests.

I, though, when I do Program.Main (), it all starts with unit tests, but somehow remembers the results of the last test.

How can I write unit tests that will be isolated from each other (I do not need the clean () functions - I want it to start with a new "everything"),

+8
c # unit-testing singleton
source share
5 answers

Short version: do not record your singleton as single. Write them like regular classes and call them using the Inversion of Control container, where you configured the class as a singleton.

This way you can fully test the class, and if you decide today or tomorrow that singleton is not suitable for lifestyle, just change the configuration of the IoC container.

+15
source share

Well, that seems logical, since your singleton is probably at the AppDomain level. So while you are in the same AppDomain, there will be only one for all your tests.

I don’t know how this framework is handled, but if you want to do it yourself, you will have to create a separate AppDomain for each test, but I was told that it will be quite difficult: http://msdn.microsoft.com/en-us/ library / 6s0z09xw.aspx

+2
source share

look at this singleton test with singletones

I would also recommend using fake frameworks like Moq

to isolate your dough

+1
source share

When trying to test singleton itself, a solution may be possible:

public class Singleton { private static Singleton _Instance; public static Singleton getInstance() { if (_Instance == null) { _Instance = new Singleton(); } return _Instance; } private Singleton() { } public static resetForTesting() { _Instance = null } } 

So, in your unit testing module, you should call Singleton.resetForTesting() before each unit test.

Note The disadvantage of this approach is the lack of a code level restriction that would prohibit anyone from invoking this method in production code, although it is intended only for use with test code. Therefore, you will have to rely on the documentation to pass this on to other people.

0
source share

You can add the setter property to your singleton class, which will reassign the singleton instance. Thus, in tests, you can drown / ridicule your singleton.

0
source share

All Articles