0

I'm trying to assert an exception which happens in an async method.
Unfortunately, the assertion doesn't work.

I've made sure via debugging, that the throw new Exception(...) is called in the SaveCategoriesAsync(...) method.

The method with the Action normally works for unit tests... but it seems that it doesn't work with async.

I'm using FakeItEasy as mocking framework and FluentAssertions as assertion framework.

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

What do I have to change to be able to assert the exception?

Thanks in advance

xeraphim
  • 4,375
  • 9
  • 54
  • 102
  • You cannot catch exceptions in different threads. If the ShouldThrow() method doesn't do something special, it wont work. Check if your assertion framework provides a way for async actions to detect exception or write your own. – helb Oct 27 '17 at 12:37

2 Answers2

2

If it is easy to change the test runner, consider NUnit. Then your code would look:

...
Assert.ThrowsAsync<Exception>(async () => await this.testee.SaveCategoriesAsync(new List<int>());
...
1

The answer is actually quite similar to what I tried. But with async, you have to use a Func<Task> instead of an action:

[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>();
}
xeraphim
  • 4,375
  • 9
  • 54
  • 102