【问题标题】:Throw ExpectedException TimeoutException with Stub is not working c#Throw ExpectedException TimeoutException with Stub is not working c#
【发布时间】:2017-09-22 17:17:38
【问题描述】:

我有这个单元测试,我一直在尝试对其抛出异常,但我无法做到,请你帮帮我吗?

    [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);
    }

【问题讨论】:

  • 在行为中,而不是 await do .Wait 方法。 // 执行 commandHandler.HandleAsync(deleteModel, token).Wait();试试看。

标签: c# .net unit-testing stub timeoutexception


【解决方案1】:

单元测试不等待异步方法。没有人要求异步方法的结果。您需要执行 .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();
}

【讨论】:

    猜你喜欢
    • 2022-11-20
    • 1970-01-01
    • 2022-12-26
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 2022-12-28
    相关资源
    最近更新 更多