我如何单元测试这个异步方法,它(正确)抛出一个异常?抛出、单元测试、异常、正确

由网友(卑恋)分享简介:我在一个接口下面的方法。I have the following method in an interface..Task SearchAsync(TU searchOptions);的伟大工程。works great.现在我试图做一个单元测试来测试出问题的时候 - 与code...

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

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));
阅读全文

相关推荐

最新文章