NUnit可以期待超时吗? [英] Can NUnit expect a timeout?
问题描述
我想测试一种在特定情况下希望阻止的方法.
I would like to test a method that I am expecting to block in a specific situation.
我尝试了TimeoutAttribute
和ExpectedExceptionAttribute
的组合:
[Test]
[Timeout(50), ExpectedException(typeof(ThreadAbortException))]
public void BlockingCallShouldBlock()
{
this.SomeBlockingCall();
}
不幸的是,这不起作用,因为我在此处读到的ThreadAbortException
似乎被NUnit本身抓住了.
Unfortunately this does not work as the ThreadAbortException
I was reading about here seems to get caught by NUnit itself.
是否有一种方法可以预期超时(使用NUnit)?
Is there a way to expect timeouts (with NUnit)?
推荐答案
对于这样的问题,我可能会使用 Task.Wait(int)
或
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);
}
但是请注意,这将在后台线程上调用SomeBlockingCall
,但是对于大多数单元测试而言,这不是问题.
Be warned however, this will invoke SomeBlockingCall
on a background thread, but for the majority of unit tests, this is a non-issue.
这篇关于NUnit可以期待超时吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!