[英]Unit Testing Synchronous Method With Code Calling Task
Given the following class: 给定以下类别:
public class TestAttribute : ActionFilterAttribute
{
public bool SomeExampleBool = false;
public override void OnActionExecuting(HttpActionContext actionContext)
{
Task.Factory.StartNew(() => { SomeExampleBool = true; });
}
}
How would you write a valid unit test for OnActionExecuting
that Asserts that SomeExampleBool
is equal to true
? 您如何为
OnActionExecuting
编写有效的单元测试,以断言SomeExampleBool
等于true
?
When writing a unit test and calling OnActionExecuting
, then calling the Assert, the logic executes on a thread that will not have executed yet. 当编写单元测试并调用
OnActionExecuting
,然后调用Assert时,逻辑将在尚未执行的线程上执行。 So the Assert fails. 因此断言失败。 Would you try something like
Thread.Sleep
for a couple of seconds? 您会尝试几秒钟的
Thread.Sleep
东西吗? Seems like a hack. 好像是hack。 I'm sure there is a better way that I'm not thinking of but I'm reaching out to the community for some help.
我敢肯定,我没有想到更好的方法,但是我正在寻求社区的帮助。
You'll need to expose the Task
returned by StartNew
to anyone that you want to be able to: 您需要将
StartNew
返回的Task
公开给您希望能够进行以下操作的任何人:
Since you're not exposing the return Task
to anyone, you're just dropping it on the floor, there's no way for anyone else to wait on it, or run a continuation when it's done. 由于您没有将return
Task
暴露给任何人,因此您只是将它放在地板上,所以其他任何人都无法等待它,或者在完成后继续运行。 Typically you'd return the Task
from that method. 通常,您将从该方法返回
Task
。 If you can't, because it's an event handler, then you could potentially store the Task
in a field or some other form of state that the caller would be able to access. 如果不能,因为它是事件处理程序,则可能会将
Task
存储在调用者将能够访问的字段或某种其他形式的状态中。
Task.Factory.StartNew
will return an instance of a Task
. Task.Factory.StartNew
将返回Task
的实例。 If you call task.Wait()
, you'll be guaranteed that the task will complete before executing the next line. 如果调用
task.Wait()
,则可以确保任务将在执行下一行之前完成。 You should be able to just Wait
for the task to complete, and then run your assertions after that. 您应该只能够
Wait
任务完成,然后再运行断言。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.