我有这个单元测试,而且我一直试图对它进行例外处理,但是我无法做到,请你能帮助我吗?
[TestMethod]
[ExpectedException(typeof(TimeoutException))]
public async Task HandleAsyncDeleteModel_WhenRepositoryFails_ThrowsException()
{
//Arrange
var token = new CancellationToken();
var deleteModel = new DeleteProcessCommand(_img, _tnt, _pro, _url);
var writeRepository = new StubIWriteRepository<Dto>()
{
DeleteIfExistsAsyncGuidGuidGuidCancellationToken = (img, tnt, pro, tkn) =>
{
throw new TimeoutException();
}
};
var Logger = new StubILogger();
var commandHandler = new CommandHandler(Logger, writeRepository, null, null, null, null, null, null);
//Act
await commandHandler.HandleAsync(deleteModel, token);
}
答案 0 :(得分:0)
单元测试不等待异步方法。没有人要求异步方法的结果。你需要做一个.Wait来迫使它等待结果。
[TestMethod]
[ExpectedException(typeof(TimeoutException))]
public async Task HandleAsyncDeleteModel_WhenRepositoryFails_ThrowsException()
{
//Arrange
var token = new CancellationToken();
var deleteModel = new DeleteProcessCommand(_img, _tnt, _pro, _url);
var writeRepository = new StubIWriteRepository<Dto>()
{
DeleteIfExistsAsyncGuidGuidGuidCancellationToken = (img, tnt, pro, tkn) =>
{
throw new TimeoutException();
}
};
var Logger = new StubILogger();
var commandHandler = new CommandHandler(Logger, writeRepository, null, null, null, null, null, null);
//Act
commandHandler.HandleAsync(deleteModel, token).Wait();
}