Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happened to Assert.DoesNotThrowAsync() in xUnit?

Tags:

c#

xunit

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?

like image 475
der_michael Avatar asked Aug 27 '15 18:08

der_michael


People also ask

What is Assert in xUnit?

In xUnit and many other testing frameworks, assertion is the mean that we conduct our test. In other word we assert an expectation that something is true about a piece of code. There are many different types of assertion in xUnit that we can use.

How do you Assert two objects are equal in xUnit?

You'll have to implement IEquatable<T> for your objects, and then Assert. Equals will work. Assert. Same() compares by reference; it asserts that Obj1 and Obj2 are the same object rather than just looking the same.

How do I expect exception in xUnit?

If you do want to be rigid about AAA then you can use Record. Exception from xUnit to capture the Exception in your Act stage. You can then make assertions based on the captured exception in the Assert stage. An example of this can be seen in xUnits tests.

How do you test if a method throws an exception in xUnit?

You can check if a method call throws an exception by using the Assert. Throws method from xUnit.


2 Answers

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); } 
like image 164
slasky Avatar answered Sep 18 '22 13:09

slasky


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(); } 
like image 38
Marcio Rinaldi Avatar answered Sep 19 '22 13:09

Marcio Rinaldi