nunit3试图测试一个线程在我中止线程时抛出ThreadAbortException

时间:2017-04-26 09:38:43

标签: c# multithreading visual-studio nunit-3.0

使用Nunit 3

测试用例:我创建并启动的一个线程,当我中止线程时抛出一个ThreadAbortException

预期结果:传递(用于测试以确认发生了ThreadAbortException)

结果失败,错误

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

Nunit 3测试代码:

[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输出窗口:输出窗口正确

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

问题: nunit 3测试没有向我确认是否抛出了异常

1 个答案:

答案 0 :(得分:1)

CLR将在catch块后自动重新提升ThreadAbortException(有关详细信息,请参阅此answer)。

您可以尝试在测试代码的catch块中使用Thread.ResetAbort()方法 - 请务必阅读备注。

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

我和我的测试跑步者一起工作。 YMMV。