Unit Testing
Learn about unit testing through practices like Test-Driven Development (TDD).
Fixing bugs in code is expensive. The earlier a bug is discovered in the development process, the less expensive it will be. Unit testing is a good way to find bugs early in development. Some developers even follow the principle that programmers should create unit tests before writing code, called Test-Driven Development (TDD).
Microsoft has a proprietary unit testing framework known as MSTest
. There is also a framework named NUnit
. However, we will use the free and open-source third-party framework xUnit.net
. xUnit
was created by the same team that built NUnit
, but they fixed the mistakes they felt they made previously. xUnit
is more extensible and has better community support.
Understanding types of testing
Unit testing is just one of many types of testing, as described in the following table:
Type of Testing | Description |
Unit | Tests the smallest unit of code, typically a method or function. Unit testing is performed on a unit of code isolated from its dependencies by mocking them if needed. Each unit should have multiple tests: some with typical inputs and expected outputs, some with extreme input values to test boundaries, and some with deliberately wrong inputs to test exception handling. |
Integration | Tests if the smaller units and larger components work together as a single piece of software. Sometimes involves integrating with external components we do not have source code for. |
System | Tests the whole system environment in which our software will run. |
Performance | Tests the performance of our software; for example, our code must return a web page full of data to a visitor in under 20 milliseconds. |
Load | Tests how many requests our software can handle simultaneously while maintaining required performance, for example, 10,000 concurrent visitors to a website. |
User Acceptance | Tests if users can happily complete their work using our software. |
Creating a class library that needs testing
Creating a class library that needs testing first, we will create a function that needs testing. We will create it in a class library project separate from a console app project. A class library is a package of code that can be distributed and referenced by other .NET applications:
Step 1: Use your preferred coding tool to add a new Class Library or classlib project named CalculatorLib
to the Chapter04
workspace/solution
. We will have created about a dozen new console app projects and added them to a Visual Studio 2022 solution or a Visual Studio Code workspace. The only difference when ...