Primarily XUnit leverages some new features to help developers write cleaner test, as tests should be kept clean and treated as first-class citizens.
- November 2, 2018
Special thank you for Channel 9 and @skimedic for sharing his unit testing knowledge.
XUnit leverage some of the new features to help developers write cleaner test, as tests should be kept clean and treated as first-class citizens.
Where to get it and how to add it to your projects (2 ways)
It does work with live unit testing
Add [Fact] attribute on a method to mark it as a test
Use Theory and InlineData as mechanism to pass data into the test
[Theory] attribute to mark a method as a test and setup incoming parameters (2 approaches InlineData and MemberData)
[InlineData(1,2,3)
approach to pass data into the test method (add additional InlineData attributes for multiple runs of same test)
MemberData(nameof(IEnumerable<object>
In the example below we are using a method to return data to be used (however this method could also read data from other files such as text or excel to be returned)
approach to pass data into the test method
xUnit runs it’s tests in parallel to take advantage of today’s processors
tests within one class are run serial
tests in multiple classes are run parallel
can be disabled by creating a test collection (add attribute [Collection({name})], and all within the same collection will be run serial
in order to test that an exception is thrown
Assert.Throws<InvalidOperationException>(() => ThrowAnError());
Setup/Teardown
There are no [Setup] and [Teardown] attributes, this is done using the test class’ constructor and an IDisposable. This encourages developers to write cleaner tests.
use constructor in place of Setup attributes to prepare tests
now use IDisposable to replace teardown i.e. public class ATestClass : IDisposable
public void Dispose() { //something here to clean up }
Notes
References:
https://xunit.github.io/docs/why-did-we-build-xunit-1.0.html https://dev.to/hatsrumandcode/net-core-2-why-xunit-and-not-nunit-or-mstest--aei https://channel9.msdn.com/Shows/Visual-Studio-Toolbox/Unit-Testing-xUnit https://xunit.github.io/