84

I migrated my unit test project from version 2.0.0-beta-{something} to 2.0.0 (stable) through NuGet. It seems like Assert.DoesNotThrowAsync() is not available anymore.

For Example:

[Fact]
public void CanDeleteAllTempFiles() {
    Assert.DoesNotThrowAsync(async () => DocumentService.DeleteAllTempDocuments());
}

Results in

DocumentServiceTests.cs(11,11): Error CS0117: 'Xunit.Assert' does not contain a definition for 'DoesNotThrowAsync' (CS0117)

A workaround would be to omit the test. Is there any better solution?

slasky
  • 2,726
  • 4
  • 27
  • 36
der_michael
  • 3,151
  • 1
  • 24
  • 43

3 Answers3

130

I just wanted to update the answer with current information (Sep 2019).

As Malcon Heck mentioned, using the Record class is preferred. Looking at xUnit's Github, I see that a current way to check for lack of exceptions thrown is like this

[Fact]
public async Task CanDeleteAllTempFiles() {
    var exception = await Record.ExceptionAsync(() => DocumentService.DeleteAllTempDocuments());
    Assert.Null(exception);
}
slasky
  • 2,726
  • 4
  • 27
  • 36
40

OP is asking about async, but if anyone else got here looking for non-async equivalent then:

[Fact]
public void TestConstructorDoesNotThrow()
{
    var exception = Record.Exception(() => new MyClass());
    Assert.Null(exception);
}
RJFalconer
  • 10,890
  • 5
  • 51
  • 66
34

As you can see in this discussion, the recommended way to test if a method does not throw in xUnit v2 is to just call it.

In your example, that would be:

[Fact]
public async Task CanDeleteAllTempFiles() {
    await DocumentService.DeleteAllTempDocuments();
}
Marcio Rinaldi
  • 3,305
  • 24
  • 23
  • 19
    The link to the discussion is correct, but the solution they got is not this one. The recommendation is not just to call the method. In fact, if this method throws an exception, xUnit will throw the exception. To check if the method does not throw an exception the recommendation is to use the Record class. – Maicon Heck Apr 07 '19 at 07:20
  • @MaiconHeck why is Record needed? What's wrong with Marcio's approach? Looks simpler and more memorable for me. – nawfal Mar 23 '23 at 23:57
  • @nawfal you called a method (`act`), but assert nothing. Should other devs guess in MR when unit test is complete and we check that method doesn't throw exceptions or when you forgot to complete your unit test? – Mark Twain Mar 30 '23 at 08:16
  • @MarkTwain Fair point, though I would just leave a comment. – nawfal Mar 31 '23 at 09:56