Best Practices to write Unit test with .Net Core

|
| By Webner

Introduction

In programming, the Unit test is used to test the source code of a particular method. In this method, we can check if the code is ready to deploy or not. It also improves code quality. In this test, we can test all the positive and negative cases of one function.

Characteristics of a good unit test

  • Fast: It takes very little time to execute a large number of test cases.
  • Isolated: These tests are standalone, have no dependencies on any other factor Like any external API, database.
  • Repeatable: It should always return the same result.
  • Self-Checking: It automatically checks that a particular method is passed or failed.

The following are the best practices to write Unit test with .Net core:

1. Naming your tests

The naming convention is most important to express the intent of the unit test methods. A good method name can tell the whole story of the method.
The name of your method should consist of three parts:

  • The name of the method is being tested.
  • The scenario under which it’s being tested.
  • The expected behavior or result when a method is invoked.

2. Arranging your tests

Arrange, Act and Assert are common patterns for unit tests and also known as AAA. It consists of three main actions. You can see the Arrange, Act, Assert implementation in the below example. There are a number of assert methods to be performed on the actual result and the expected result. Like: Assert.Equal(expected, actual); and many more.

  • Arrange your objects
  • Act on an object.
  • Assert that something is as expected.

Bad Approach
If you see the example below, it is not clear from the name of the method what functionality is being tested.
[Fact] public void Test_Method()
{
// Arrange
var Calculator = new Calculator();
// Act
var actual = Calculator.Add("0");
// Assert
Assert.Equal(0, actual);
}

Better Approach
[Fact] public void Add_SingleNumber_ReturnsSameNumber()
{
var Calculator = new Calculator();
var actual = Calculator.Add("0");
Assert.Equal(0, actual);
}

Here, you can see that the method name itself is telling that in this method, we are adding a single number and returning the same number.

3. Avoid multiple asserts in a single method like below: –

public void GetUserSession_ReturnsException()
{
Assert.Throws(() => Calculator.Add(null));
Assert.Throws(() => Calculator.Add("a"));
}

Avoid logic in the test cases:- You have to follow the AAA(Arrange, Act, Assert) approach to writing unit test cases.

Note:- Do not create unit tests in the same project instead create a new project to write a unit test like “XUnitTestProject1.Test” for the project “XUnitTestProject1” and if possible write a specific layer unit test in a single directory. Like, we can write Business layer test cases in the respective directory “XUnitTestProject1.Business”.

Leave a Reply

Your email address will not be published. Required fields are marked *