Can NUnit expect a timeout?

烈酒焚心 提交于 2019-12-08 19:42:18

问题


I would like to test a method that I am expecting to block in a specific situation.

I tried a combination of the TimeoutAttribute and ExpectedExceptionAttribute:

[Test]
[Timeout(50), ExpectedException(typeof(ThreadAbortException))]
public void BlockingCallShouldBlock()
{
    this.SomeBlockingCall();
}

Unfortunately this does not work as the ThreadAbortException I was reading about here seems to get caught by NUnit itself.

Is there a way to expect timeouts (with NUnit)?


回答1:


For a problem like this, I would probably use Task and Task.Wait(int) or Task.Wait(TimeSpan). For example:

[Test]
public void BlockingCallShouldBlock()
{
    var task = Task.Run(() => SomeBlockingCall());
    var completedInTime = task.Wait(50); // Also an overload available for TimeSpan
    Expect(completedInTime, Is.False);
}

Be warned however, this will invoke SomeBlockingCall on a background thread, but for the majority of unit tests, this is a non-issue.



来源:https://stackoverflow.com/questions/19406672/can-nunit-expect-a-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!