At university, you must have learned the concept of Unit Test in “Software Quality Testing.” In simple terms, unit testing is the code used to test the code we have written.
Some characteristics of unit tests:
- The unit code test must be short, easy to understand, and easy to read.
- Each unit test is a separate, independent unit, independent of other units.
- Each unit test is a method in the test class; the method name is also the UnitTest name. Therefore, we should name the function clearly, stating what this unit test is (Test_A_Do_B); the method name can be very long.
- Unit Tests must be fast, as they will be run to check for errors each build. Therefore in unit testing should limit time-consuming tasks such as I / O calls, database, network, …
- Unit Test should test each object separately. Ex: Unit Test for Business Class, then adjust the Test that Business Class itself should not use hooked classes with it (DataAccess Class, for example).
Some of you will ask: “Oh well, in the business class, do we have to call data access?”, And “our code is very sticky, how can we test each class separately.”
- To write unit tests, your classes must have a “loose coupling” relationship. If not writing unit tests means that the classes are stuck together too tightly, it will be difficult to change later. Apply the SOLID principles to your code, writing code with a “how to write a unit test” concept will make your code more flexible and more comfortable to test.
- Regarding Business Class and Data Access, classes should not be called directly to each other but through interfaces. When unit tests, we will replace these interface implementations with mock classes, replacing the actual data access class. I will be clear about this in future articles about Inversion of Control, Dependency Injection.
Some benefits of Unit Test:
- If you write a Unit Test carefully, your code will be slightly error-free because Unit Test will detect errors for you.
- Detects slow and inefficient functions through Unit Test runtime.
- Increase confidence when coding because the Unit Test has detected errors.
- When refactoring code, edit code or add new functions, Unit Test ensures the program runs correctly, detecting potential errors that we miss.
Recently, the Test Driven Development (TDD) development model has been getting hot, applied a lot. This model is based on the concept: For each function, we write the Unit Test first, then write the function implementation function to unit test pass.
Unit Test in C # with NUnit
Previously, to write Unit Test in C #, we often had to create a separate test project using Microsoft’s MSTest library. MSTest supports many functions: Test data from the database, measure system performance, export report data. However, because MSTest comes with Visual Studio, it cannot be run separately, it is quite heavy, so NUnit is more popular. NUnit has its own set of runners, which can run UnitTest independently without VisualStudio, besides it also supports some features that MSTest does not have (parameter test, Assert Throw).
If you have never written Unit Test, starting with NUnit is also a good choice. First, let’s create a project console in Visual Studio. We write a class Calculator with two functions Add and Subtract:
public class Calculator
public int Add(int x, int y)
return x + y;
}public int Subtract(int x, int y)
return x - y;
Now, we will write UnitTest to test these two functions. Normally, the Unit Test code will be located in a separate Test project, so we will create a new project, adding “.Test” after the name. Remember to choose the project type as Library Class.
On the new project, click Tools -> Library Package Manager -> Package Manager Console, type: “Install-Package NUnit -Version 2.6.4” to install NUnit. We create a new class named CalculatorTest. Let’s start writing:
public class CalculatorTest
private Calculator _cal;
public void Setup()
_cal = new Calculator();
public void OnePlusOneEqualTwo()
Assert.AreEqual(2, _cal.Add(1, 1));
public void TwoPlusTwoEqualFour()
Assert.AreEqual(4, _cal.Add(2, 2));
public void FourPlusOneEqualFive()
Assert.AreEqual(5, _cal.Add(4, 1));
Explain some annotation:
- Annotation [TextFixture] is placed at the beginning of the class containing the unit tests, marking this as a set of unit tests.
- Annotation [SetUp] to highlight the setup function. This function will be run at the beginning of each unit test.
- Annotation [Test] to mark the function below is a unit test. Many times when you have finished writing unit tests, but you don’t see the unit tests; the reason is to forget about this annotation.
To run the Unit Test, we need to install NUnit.TestAdapter, which is a runner that allows running NUnit Unit Test in Visual Studio. You can also use either of the following:
- Download NUnit GuiRunner, open the DLL file of the project test, the unit tests will appear to run.
- Download Reshaper. Reshaper also has a built-in Runner that allows running the Unit Tests of NUnit.
To install TestAdapter for Visual Studio, go to Tools, Extensions, and Updates, find NUnit and install it. After installing, remember to Restart Visual Studio.
Click Test -> Run -> All Tests to start running. We will see all the cases that have passed, the green color as in the image.
We intentionally modified the code to run the code wrong. Rerunning Unit Test, we will see that the cases have failed. Unit Test has automatically captured the program errors for you already. Click on each test case; we will see the desired results in the “Excepted,” the code results in the “But was.”
The purpose of the article is to guide you to start writing Unit Test for C # with NUnit so that I will stop here. Thank you and see you again.