I have a timer in my class that is I only ever want one of so I have a static reference to it in my Main. During integration tests (not in normal runtime) it gets instantiated multiple times through different tests.
My idea was to create a Singleton that inherits all the functionality to ensure there is only ever one. I was wandering if this is sensible or will I come across some pitfalls I haven’t thought of yet?
e.g In my Integration Test I am currently using
[TestMethod]
public void SomeTimerTest()
{
MyTimer t = new Mytimer();
t.Start();
}
whereas after this change I would use
[TestMethod]
public void SomeTimerTest()
{
//creates a new instance or retrieves an already existing one
MytimerSingleton.Instance.Start();
}
thus avoiding the chance I might have two running – (as they access a single resource in the file system)
Update: Corrected terminology from unit testing to integration testing.
No. I would say thats a bad idea ™.
A unit test needs to test a single unit of functionality. Really there should only ever be one class instantiated in any one test.
By making your Timer class a singleton, I get the feeling you will be testing a class that just happens to be using your Timer. This test will then be testing two classes. Don’t do it!
Instead :
When testing the class that uses your Timer, you should create a mock of your Timer class and pass that in to your class under test. Then if you break your Timer class, the Timer class tests fail, but all the other classes will still pass. Debugging is a piece of cake as you will instantly know it is your Timer class that is broken.