1

I noticed in my code that a class that created a new thread that was never properly cleaned up. The unit test of that piece of code succeeded, but on the console there was a warning saying that a System.AppDomainUnloadedException had occurred. This can be reproduced with the following code snippet

    [TestMethod]
    public void StartNewThread_ThreadNotStopped_StillSucceeds()
    {
        var thread = new Thread(DoNothingForEver);
        thread.Start();
    }

    private void DoNothingForEver()
    {
        while (true){/* do nothing */}
    }

When developing such unit tests, the developer is responsible for ensuring that such exceptions don't occur, but at work I've seen this happen too often. Even worse, I've witnessed that when code with successful unit tests was refactored, the unit tests would still succeed but an unnoticed exception was thrown. When digging into this issue, it became clear that the refactored code was not working properly, and as such, the unit test had little added value.

Is there any way that I can instrument my test projects such that MsTest will fail in such situations?

Chandan Kumar
  • 4,570
  • 4
  • 42
  • 62
SimonAx
  • 1,176
  • 1
  • 8
  • 32
  • Unit Testing Threading is a pain, as this post shows: http://stackoverflow.com/questions/12159/how-should-i-unit-test-threaded-code – Jason H Mar 22 '17 at 08:43
  • 1
    If your class need to be properly cleaned up, then it is good candidate to implement `IDisposable` interface. The purpose is that test method to return only when all necessary assertion is executed. Where in your case you start thread and method return without waiting for result – Fabio Mar 22 '17 at 08:43
  • @Fabio Implementing IDisposable was indeed my solution, but only after I noticed the warnings in the output window. Implementing IDisposable in every unit test class is not an option. The question is thus, how can I make exceptions thrown during cleanup cause the whole unit test to fail? – SimonAx Mar 22 '17 at 08:52
  • Are you talking about test class or class under the test? If you testing `DoNothingForEver` method, then what is purpose of executing it on another thread? – Fabio Mar 22 '17 at 08:57
  • The code snippet is certainly a crude simplification of the actual problem. In the real code, a thread was started in the constructor of a class that should never go out of scope (i.e. a singleton), This newly created thread is responsible for heartbeat functionality, so it has to be run in a separate thread. The question is thus not how and when to create threads, but how I can force a unit unit test to fail if an exception is thrown during cleanup. – SimonAx Mar 22 '17 at 09:28

0 Answers0