Introduction to Unit Testing

Learn how to set up a test project, write unit tests using the Arrange-Act-Assert pattern, and execute them via the .NET CLI.

As applications grow, manually verifying every class becomes impossible. Unit testing automates this process by verifying individual units of code in isolation. A unit is typically a single method or a specific behavior within a class.

In .NET, developers create a separate test project that references the main application code. The .NET ecosystem supports several testing frameworks, including xUnit, NUnit, and MSTest. We use xUnit for these examples because it is the default testing framework generated by modern .NET templates.

Setting up the test environment

To run tests, the .NET Command Line Interface (CLI) requires a specific project structure. We need a main application project, a separate test project, and a reference linking the two.

We can generate this structure using the terminal.