xUnit.net
Create a directory structures for projects
Open a shell window. Create a directory structure with the below commands:
The directory and file structure thus far should be as follows:
Create the source project
Make the Calculator
directory the current directory, and create a new project using dotnet new classlib
, and then rename Class1.cs
to Calculator.cs
To use test-driven development (TDD), you first create a maths implementation of the Calculator.cs
class:
Creating the test project
Make the Calculator.Tests
directory the current directory, and create a new project using dotnet new xunit
.
The test project requires other packages to create and run unit tests. Add the Calculator
class library as another dependency to the project. Use the
Rename UnitTest1.cs
to CalculatorTests.cs
Creating the first test
The Fact
attribute indicates a test method that is run by the test runner. Run dotnet test
to build the tests and class library for running the xUnit test runner contains the program entry point to run your tests.
Creating the first theory
xUnit.net includes support for two different major types of unit tests:
Facts are tests which are always true. They test invariant conditions.
Theories are tests which are only true for a particular set of data.
Theories can be useful when we need to run multiple tests with different parameters instead of duplicate the test method, see the example code below:
Passing array in InlineData params
Capturing output in unit tests
Unit tests have access to a special interface which replaces previous usage of Console
and similar mechanisms: ITestOutputHelper
. In order to take advantage of this, just add a constructor argument for this interface, and stash it so you can use it in the unit test.
Create a test base
Inherits the TestBase
Worth Reading
Last updated
Was this helpful?