开发者

c# singleton inheriting from non-singleton for integration testing

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开发者_如何学Python 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 (tm).

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.


That's a pretty bad idea, because it links your unit tests together, so they aren't independent any more. This can lead to side effects with some tests failing only, when executed together with other tests or the other way around. Avoid it if possible. The same is true for static classes and members.

Update:
Now that you clarified your question, let me say this:

  1. Your unit tests should be self contained, that means, you shouldn't access the file system, as this again introduces the possibility of side effects between your tests.
  2. You can introduce a TearDown method that is called after each test. In this method you could ensure that the timer is cleaned up.


Could you reorganize your testing? In essence if you create a singleton there really can only be one so if your tests require multiple timers then you should reorganize them to work with an already present and active timer.


Who gets to stop the timer? If there's only one, then any call to Stop() will stop the timer.

You might be better off using a Fixture (like IUseFixture<> in XUnit.Net) to handle this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜