Creating tests with xUnit and .Net 5
Geraldo Alves Simao Junior
.NET Core | C# | ASP.NET Core | Microservices | Web Api | SQL Server | Docker | Azure
xUnit.net is a modern testing framework that is also used by the .NET development team at Microsoft.
It’s often more expensive, time-consuming, and stressful to fix software bugs after they’ve been released into production environments. A good set of automated tests helps verify that the application is working as expected and helps prevent bugs from going into production.
The main idea is to show how simple and easy it is to start writing automated tests with xUnit to verify that your app is working as expected and to help avoid bugs.
Using xUnit
To start, let’s create a Class Library .Net Core project to simulate the application in Visual Studio.
Let’s enter a name for the project.
Let’s select Framework .NET 5.
Let’s create a class named Calculator.
Now let’s create a project of type xUnit Test Project .Net Core to create our tests.
A good pattern to follow is to create the test project name with the same name as the project to be tested followed by the “.Test†suffix as shown in the image below.
领英推è
Again, let’s select Framework .NET 5 for the test project.
Create a class named CalculatorTests and our first simple test method named Calculator_Multiply_ReturnMultiplication decorated with the attribute [Fact].
Let’s follow the AAA principle: Act, Arrange and Assert in the methods.
Let’s create a slightly more complex scenario by creating a new method with the [Theory] attribute, with it you can test a subset of parameterized data that can be dynamically inserted.
These subsets can be made available in different ways, such as: [InlineData], [ClassData], and [MemberData].
For this example we are going to use [InlineData], it allows executing a test method several times passing different values to each interaction as parameters.
With Test Explorer, it is possible to run, debug and analyze the created tests.
Conclusion: We can see that it is very easy to generate tests with xUnit following naming standards and the AAA principle: Act, Arrange and Assert.
Full source code: https://github.com/geraldsimon/xUnit-and-.Net-5