Xunit中的测试异常() [英] Test Exceptions in Xunit ()
问题描述
我正在尝试使用此方法编写Xunit测试:
I am trying to write Xunit test on this method:
public async Task<IEnumerable<T>> RunSQLQueryAsync(string queryString)
{
try
{
//do something
}
catch (DocumentClientException e)
{
throw new InvalidOperationException(e);
}
}
这是单元测试:
[Fact]
public async virtual Task Test_Exception()
{
var queryString = "SELECT * FROM c";
var exception = Record.ExceptionAsync(async () => await classname.RunSQLQueryAsync(queryString));
Assert.NotNull(exception);
Assert.IsType<DocumentClientException>(exception);
}
但是该方法失败了,并显示:
But the method failed and it says:
消息:Assert.IsType()预期失败:System.DocumentClientException实际:
System.Threading.Tasks.Task`1 [[System.Exception,System.Private.CoreLib,版本= 4.0.0.0,文化=中性,PublicKeyToken = xxx]]
Message: Assert.IsType() Failure Expected: System.DocumentClientException Actual:
System.Threading.Tasks.Task`1[[System.Exception, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=xxx]]
当我调试测试时,它不会进入catch块.所以我的问题是如何使单元测试期望方法 RunSQLQueryAsync
具有 DocumentClientException
?
When I debugged the test, it doesn't go to the catch block. So my question is how to make the unit test expects the method RunSQLQueryAsync
to have DocumentClientException
?
推荐答案
测试未在等待从 Record.ExceptionAsync
返回的 Task< Exception>
实际上是在 Task
本身上完成的.
The test is not awaiting the Task<Exception>
returned from Record.ExceptionAsync
so the following assertion is actually being done on the Task
itself.
同样,被测方法消耗 DocumentClientException
并引发 InvalidOperationException
的新异常,因此这是应有的类型.
Also the method under test consumes the DocumentClientException
and throws a new exception of InvalidOperationException
so that is the type that should be expected.
[Fact]
public async virtual Task Test_Exception() {
//Arrange
var queryString = "SELECT * FROM c";
//Act
var exception = await Record.ExceptionAsync(() =>
classname.RunSQLQueryAsync(queryString));
//Assert
Assert.NotNull(exception);
Assert.IsType<InvalidOperationException>(exception);
}
在 Record.ExceptionAsync
还假设被测类已经被设置为具有模拟的依赖关系,该依赖关系将在所提供的代码片段的//做某事
部分中引发所需的异常.
The assumption is also that the class under test has been setup with a mocked dependency that will throw the desired exception in the //do something
part of the provided snippet.
这篇关于Xunit中的测试异常()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!