C# Unit Test
Unit test is an automated test that verifies if a single unit of a program works as expected. A single unit is the smallest piece of code that can be logically isolated in a program. Usually. it is a single method in a class.
Usually for each project with production code, we create a seperate project with unit tests. We’ll create a new project of class library type. The typical naming convention is that the testing project should be named the same as the project it tests, but it should have the Tests postfix.
We need to install following libraries through NuGet:
– NUnit
– NUnit3TestAdapter: enable us to run tests
– Microsoft.NET.Test.Sdk
We usually create one unit test class for 1 tested class. A collection of unit tests for a specific class is called a test fixture or a test suite. A single unit test is a public void method with a Test attrivute added. We can also add the TestFixture attribute to the class to mark it as a class containing unit tests, but this is not necessary, because if a class contains at least one method with the Test attribute, it will be recognized as a test fixture anyway,
Naming
A name of a unit test shall consist of 3 parts. The name of the method being tested, the exptected behavior and the scenario under which it’s being tested. Don’t hesitate to have a very long test name. It’s better to make it long and clear than short and vague. For example, SunOfEvenNumbers_ShallReturnZero_ForEmptyCollection.
Test Message
A test message is a specific description of the reason for test failure. It is optional, but it may be useful to define it if the name of the test does not carry all the information that we would like to share.