我如何单元测试这个异步方法,它(正确)抛出一个异常? [英] How can I unit test this async method which (correctly) throws an exception?

查看:385
本文介绍了我如何单元测试这个异步方法,它(正确)抛出一个异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个接口下面的方法。

I have the following method in an interface..

Task<SearchResult<T>> SearchAsync(TU searchOptions);

的伟大工程。

works great.

现在我试图做一个单元测试来测试出问题的时候 - 与code抛出一个异常

Now i'm trying to make a unit test to test when something goes wrong - and the code throws an exception.

在这种情况下,我设置我的方法抛出一个的Htt prequestException 。我的单元测试不能说我扔的例外。

In this case, I've setup my method to throw an HttpRequestException. My unit test fails to say that I threw that exception ..

var result = Should.Throw<HttpRequestException>
    (async () => await service.SearchAsync(searchOptions));

从单元测试的错误信息

the error message from the unit test is

Shouldly.ChuckedAWobbly
  VAR的结果=应
          扔
      System.Net.Http.Htt prequestException
          但不

Shouldly.ChuckedAWobbly
var result = Should
throw
System.Net.Http.HttpRequestException
but does not

所以断言框架是说:您已经预期异常,但没有被扔

当我踏上-through-的code,除100%抛出。

When I step -through- the code, the exception is 100% thrown.

任何人都可以看到我已经与我的单元测试code做错了,好吗?

Can anyone see what i've done wrong with my unit test code, please?

推荐答案

现在的问题是,你的说法框架不理解异步方法。我建议你​​跟他们提出问题。

The problem is that your assertion framework does not understand asynchronous methods. I recommend you raise an issue with them.

在此期间,您可以使用应.Throw 写自己的 MyShould.ThrowAsync

In the meantime, you can use the source for Should.Throw to write your own MyShould.ThrowAsync:

public static async Task<TException> ThrowAsync<TException>(Func<Task> actual)
    where TException : Exception
{
  try
  {
    await actual();
  }
  catch (TException e)
  {
    return e;
  }
  catch (Exception e)
  {
    throw new ChuckedAWobbly(new ShouldlyMessage(typeof(TException), e.GetType()).ToString());
  }

  throw new ChuckedAWobbly(new ShouldlyMessage(typeof(TException)).ToString());
}

和使用它作为这样的:

var result = await MyShould.ThrowAsync<HttpRequestException>
    (async () => await service.SearchAsync(searchOptions));

或稍微简单等同的:

or the slightly simpler and equivalent:

var result = await MyShould.ThrowAsync<HttpRequestException>
    (() => service.SearchAsync(searchOptions));

这篇关于我如何单元测试这个异步方法,它(正确)抛出一个异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆