代码之家  ›  专栏  ›  技术社区  ›  xeraphim

单元测试在异步方法中引发异常[重复]

  •  0
  • xeraphim  · 技术社区  · 8 年前

    我试图断言一个发生在异步方法中的异常。
    不幸的是,这个断言不起作用。

    我已通过调试确保 throw new Exception(...) 在中调用 SaveCategoriesAsync(...) 方法

    具有 Action 通常适用于单元测试。。。但它似乎不适用于异步。

    我正在使用 虚假的 作为模拟框架和 FluentAssertions公司 作为断言框架。

    [TestMethod]
    public void SaveCategoriesAsync_When_Then()
    {
        A.CallTo(() => this.articleRepository.GetArticles(A<IList<long>>._)).Returns(new List<ArticleModel>());
    
        Action action = async () => await this.testee.SaveCategoriesAsync(new List<int>());
    
        action.ShouldThrow<Exception>();
    }
    

    提前感谢

    2 回复  |  直到 8 年前
        1
  •  2
  •   Mykhailo K.    8 年前

    如果更换测试运行器很容易,请考虑 NUnit

    ...
    Assert.ThrowsAsync<Exception>(async () => await this.testee.SaveCategoriesAsync(new List<int>());
    ...
    
        2
  •  1
  •   xeraphim    8 年前

    答案实际上与我所尝试的非常相似。但是对于async,您必须使用 Func<Task> 代替动作:

    [TestMethod]
    public void SaveCategoriesAsync_When_Then()
    {
        A.CallTo(() => this.articleRepository.GetArticles(A<IList<long>>._)).Returns(new List<ArticleModel>());
    
        Func<Task> func = async () => await this.testee.SaveCategoriesAsync(new List<int>());
    
        func.ShouldThrow<Exception>();
    }