I have a singleton object in C#.
This singleton object works based on some state assigned to it.
I dont have any method to switch state of singleton object at run time. Also I dont need it as application always start in one state and remains in same state.
Problem is while writing the test cases. I have written the test cases for each state. But I cant run it because the for all test cases I have single object with one state.
How to run the tests for other state. How to re-create the object for each test?
I dont want to change the singleton object code for test cases.
Any thought or idea will be much appreciated.
This is one of the reasons why it is handy not to manage the lifetime of a class yourself, but to have an Inversion of Control (IoC) container such as Autofac or Unity do it for you. You then simply create a class, that looks like any other class, and tell your IoC container to instantiate it as a singleton.
See also An Autofac Lifetime Primer.
In the case when you cannot use an IoC container (can't think of any, but let's be flexible), you can create an internal
class that contains your "singleton"'s logic -- and this internal class is just that, an internal class, not a singleton...
internal class MyLogic
{
...
}
And then you wrap it in a public class, and make that a singleton. If you put both these classes together in a single Project, then the internal class (the implementation of your business logic) is not accessible to your application, only the public singleton version is accessible.
public sealed class MySingleton
{
private MySingleton() { Implementation = new MyLogic(); }
public static MySingleton Instance { ... }
private MyLogic Implementation { get; set; }
...
}
But then you can point out in your AssemblyInfo
that your unit-test project does have access to the internal class by using
[assembly: InternalsVisibleTo("MySolution.UnitTests")]
This way, you can unit test your logic class while your application(s) can only use it as a Singleton.
Frankly I prefer the IoC way but if that's new to you, it's probably faster to implement the above solution instead.
Good luck!