1

Using Nunit 3

Test Case: that a thread I created and started, throws an ThreadAbortException when I abort the the thread

Expected Result: to pass (for test to confirm that ThreadAbortException happened)

Result: is failed with error

NUnit.Framework.AssertionException: '  Expected:     <System.Threading.ThreadAbortException> 
But was:  null

Nunit 3 test code:

[SetUp]
    public void Setup()
    {
        _threadViewModel.CreateThread();
    }

[Test]
    public void TestThreadThrowsAbortedException()
    {
        try
        {
            _threadViewModel.RunThread();
            Assert.Throws<ThreadAbortException>(() => _threadViewModel.AbortThread());
        }
        catch (ThreadAbortException e)
        {
        }
    }

enter image description here

Visual Studio Output Window: the output window is correct

System.Threading.ThreadAbortException: Thread was being aborted. at Multthreading.ThreadRunner.WriteY()

Problem: the nunit 3 test does not confirm for me that the exception was thrown

1 Answers1

2

The CLR will automatically re-raise the ThreadAbortException after your catch block (see this answer for more information).

You can try to use the Thread.ResetAbort() method in your test code's catch block - be sure to read the remarks.

[Test]
public void TestThreadThrowsAbortedException()
{
    try
    {
        _threadViewModel.RunThread();
        Assert.Throws<ThreadAbortException>(() => _threadViewModel.AbortThread());
    }
    catch (ThreadAbortException e)
    {
        Thread.ResetAbort();
    }
}

It works for me with my test runner. YMMV.

Community
  • 1
  • 1
Christian.K
  • 47,778
  • 10
  • 99
  • 143
  • The thread.ResetAbort() does stop the ThreadAbortException from being rethrown but only in the actual code. In the test, the exceptions are not caught. I was however able to test the ThreadState. I'm currently updating the code and will post more info soon. – user2113566 May 02 '17 at 10:45