Can NUnit expect a timeout?

2019-06-17 18:58发布

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条回答
虎瘦雄心在
2楼-- · 2019-06-17 19:55

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.

查看更多
登录 后发表回答