简体   繁体   English

带有代码调用任务的单元测试同步方法

[英]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公开给您希望能够进行以下操作的任何人:

  1. Know when the operation finishes (by adding a continuation to it) 知道操作何时完成(通过向其添加延续)
  2. Know what the result is, if applicable 知道结果是什么,如果适用
  3. Know what any exceptions were, if applicable 了解什么例外,如果适用
  4. Know if it was cancelled 知道它是否被取消
  5. Wait until it has finished 等待直到完成

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM