简体   繁体   English

测试一个 function 在 xunit 的任务中抛出异常

[英]Test a function throwing an Exception in a Task in xunit

I want to test using xunit a function that run a task and throw in a that task For example:我想使用 xunit 测试运行任务并抛出该任务的 function 例如:

public void doSomething(){
     Task.Run(() =>
            {
                throw new ArgumentNullException();
            });
}

When I want to test this function by doing this:当我想通过这样做来测试这个 function 时:

[Fact]
public void TestIfTheMethodThrow()
{
   Assert.Throws<ArgumentNullException>(() => doSomething()); // should return true but return false                                                                   
}

I want that the Task.Run() finish completely then the assert can be done.我希望 Task.Run() 完全完成,然后可以完成断言。 anyone have a solution?有人有解决方案吗?

Raising and handling exceptions using TPL (the Tasks library) is slightly different, than the "standard" exception handling.使用 TPL(任务库)引发和处理异常与“标准”异常处理略有不同。 It is meaningful to evaluate only a completed task, so you need to wait for the completion, even if in this case it is an exception.仅评估已完成的任务是有意义的,因此您需要等待完成,即使在这种情况下它是一个异常。

Have a look at this MSDN article Exception handling (Task Parallel Library) .看看这篇 MSDN 文章异常处理(任务并行库)

You have two different options:您有两种不同的选择:

  • add .Wait() to the Task.Run(...)`将 .Wait( .Wait()添加到 Task.Run(...)`

     Task.Run(() => { throw new ArgumentNullException(); }).Wait();
  • or wait while the task is completed while(.task.IsCompleted) {}或等待任务完成while(.task.IsCompleted) {}

     var task = Task.Run(() =>
            {
                throw new ArgumentNullException();
            });
    while(!task.IsCompleted) {}

The test result should be then as expected - an exception is thrown.测试结果应该和预期的一样——抛出异常。

It could be, that before the Wait your test has passed sporadically - don't be irritated - in this case the task execution was faster than the test check - this is a dangerous source of subtle errors.可能是,在Wait您的测试偶尔通过之前 - 不要被激怒 - 在这种情况下,任务执行比测试检查更快 - 这是细微错误的危险来源。

You can write your method using async and await您可以使用asyncawait编写您的方法

Read this for reference Asynchronous programming with async and await阅读本文以供参考使用 async 和 await 进行异步编程

The new method look like this, and the caller will decide if want wait or not, if you call with await it will wait the task complete, otherwise it will continue without wait the task completion新方法是这样的,调用者将决定是否要等待,如果你用await调用它将等待任务完成,否则它将继续而不等待任务完成

public async Task DoSomethingAsync()
{
    if (true)
        throw new ArgumentNullException();
    await FooAsync();
}

In the test:在测试中:

[Fact]
public async Task TestIfTheMethodThrow()
{
   await Assert.ThrowsAsync<ArgumentNullException>(() => DoSomethingAsync());                
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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