Simple example of unit tests with .Net Core and xUnit
In this guide you will learn how to program automated tests in a .Net Core Web API by using xUnit . This project was developed with Visual Studio 2017 v15.
The APITest solution inside the api folder is composed by two layers: Presentation and Test.
The Presentation layer contains the Web API structure such as Controllers, Models, Swagger, AutoMapper and FluentValidation.
The Test layer contains the unit tests.
The UserController has two methods: Post and Put. Both follow the same steps:
- Copy the view model to the domain model by using the AutoMapper.
- Validate the domain model with FluentValidation and return a BadRequest in case of business exception.
- In case of success, if there's an object to return, the AutoMapper copies the domain model to another view model.
The POST method sets the user id to 1 by simulating the auto-incrementation in a database when a new user is created.
The PUT method does not return an object.
When using the Test Manager, 4 unit tests will be shown inside the xUnit project.
All the methods have the same behavior:
- Create an AutoMapper object.
- Instantiate the UserController and the User view model.
- Run the Controller method and receive the result.
- Check if the result is the same as expected.
TestPostUser_BadRequest (Post user with business exception)
TestPostUser_Ok (Post user with success)
TestPutUser_BadRequest (Put user with business exception)
TestPutUser_Ok (Put user with success)
In the Test Manager, click with the right button over UnitTestUser and debug or run the selected tests.
All the tests will be successful.
Now, let's change the UserPutVM's age from 33 to 15 and remove the id inside the TestPutUser_Ok method.
Run the test again and there will be a failure.
Why?
Because the PutUserValidation class (inside the UserController's Put method) was checking if the id was greater than zero.
As it was using the same rules from the PostUserValidation class, the age had to be equal or greater than 18 as well.
Now, let's check how the business exception will be treated outside the xUnit.
Run the API and access the Swagger page.
The Put method has the same example used in the TestPutUser_Ok method.
Remove the id and change the age as done before.
Execute the method and the business exception will be described like this:
Although no database connection was present in this project, it was possible to test POST and PUT requests because the unit tests only needed to validate the results coming from the UserController's methods.