- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Arithmetic Operators
- C# - Assignment Operators
- C# - Relational Operators
- C# - Logical Operators
- C# - Bitwise Operators
- C# - Miscellaneous Operators
- C# - Operators Precedence
- C# Conditional Statements
- C# - Decision Making
- C# - If
- C# - If Else
- C# - Nested If
- C# - Switch
- C# - Nested Switch
- C# - Switch Expressions
- C# Control Statements
- C# - Loops
- C# - For Loop
- C# - While Loop
- C# - Do While Loop
- C# - Nested Loops
- C# - Break
- C# - Continue
- C# - Foreach Loop
- C# - Goto Statement
- C# OOP & Data Handling
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Custom Exceptions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - LINQ
- C# - IEnumerable vs IEnumerator
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Tasks and Parallel Programming
- C# - Multithreading
- C# - Extension Methods
- C# - Lambda Expressions
- C# - Async and Await
- C# Modern Features
- C# - Tuples
- C# - Records
- C# - Pattern Matching Enhancements
- C# - Top-level Statements
- C# - Nullable Reference Types
- C# - What's New in C# 11 / 12 / 13
- C# - Global Usings
- C# - File-Scoped Namespaces
- C# Practical & Advanced Usage
- C# - JSON & XML Handling
- C# - Data Serialization & Deserialization
- C# - REST API Calls with Httpclient
- C# - Dependency Injection
- C# - Unit Testing with NUnit, xUnit & MSTest
- C# - Package Management with NuGet
Unit Testing with NUnit, xUnit & MSTest in C#
In software development, testing plays a important role for making sure that your application working as expected. Unit testing is the process of verifying individual units of code (like methods or classes) to ensure they work correctly in standalone.
In C#, there are three popular frameworks that manage the testing environment −
- NUnit
- xUnit
- MSTest
Each framework provides a structured way to write, run, and automate your tests, helping developers maintain code quality and prevent from future bugs.
In this chapter, let's learn what unit testing is, why it is important, and how we can test any application using the above framework.
What is Unit Testing?
In C#, unit testing involves testing small, independent units of code to verify they are giving the expected result or not.
For example, if you have a method that calculates discounts, a unit test ensures that it produces the correct result for given inputs.
Benefits of Using Unit Testing
There are following benefits of using the unit testing in your C# application −
- Detects bugs early in the development cycle.
- Simplifies debugging and maintenance.
- Improves code reliability and performance.
- Acts as documentation for your code behaviour.
- Enables continuous integration and delivery (CI/CD).
Start with Unit Testing in C#
Before writing the test case, ensure that you have installed the C# SDK and connected with VS Code.
Let's create a simple class and test them.
Before you start writing your code and tests, create a folder for your app where you will store the code, as well as a separate testing folder with the same app name. Use the command provided below.
dotnet new console -n MyApp dotnet new nunit -n MyApp.Tests dotnet sln add MyApp MyApp.Tests dotnet add MyApp.Tests reference MyApp
Inside MyApp Project
Create a file name "Calculator.cs"
namespace MyApp {
public class Calculator {
public int Add(int a, int b) => a + b;
public int Subtract(int a, int b) => a - b;
}
}
Program.cs: "Program.cs" File just your main starting point. This is not used in testing but it helps you manually run and verify your logic if needed.
using System;
namespace MyApp {
class Program {
static void Main(string[] args) {
Calculator calc = new Calculator();
Console.WriteLine("Addition: " + calc.Add(5, 3));
Console.WriteLine("Subtraction: " + calc.Subtract(10, 4));
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
Use this command, "dotnet run --project MyApp", to run this from the root directory. Following is the output −
Addition: 8 Subtraction: 6 Press any key to exit...
Now let's perform the testing of the above class "Calculator.cs" using each testing framework.
Unit Testing with NUnit
In C#, NUnit is one of the most widely used open-source testing frameworks; it provides attributes and assertions to write effective tests.
To perform the NUnit test in your project, first install the NUnit framework in your test project. Using the below command.
dotnet add package NUnit dotnet add package NUnit3TestAdapter dotnet add package Microsoft.NET.Test.Sdk
Now proceed with creating an NUnit test for the calculator mentioned above. Create a file "CalculatorTests.cs" in "MyApp.Tests" folder
using NUnit.Framework;
using MyApp;
namespace UnitTestDemo {
[TestFixture]
public class CalculatorTests {
private Calculator calculator;
[SetUp]
public void Setup() {
calculator = new Calculator();
}
[Test]
public void Add_ShouldReturnSumOfTwoNumbers() {
int result = calculator.Add(5, 3);
Assert.AreEqual(8, result);
}
[Test]
public void Subtract_ShouldReturnDifferenceOfTwoNumbers() {
int result = calculator.Subtract(10, 4);
Assert.AreEqual(6, result);
}
}
}
Unit Testing with xUnit
In C#, xUnit is an open-source, community-focused testing framework for the .NET platform that allows developers to write and run automated tests for C# and other .NET languages.
xUnit is developed by the same team that built NUnit. It highlights simplicity and supports dependency injection out of the box.
To perform the xUnit test in your project, first install the xUnit framework in your test project. Using the below command.
dotnet add package xunit dotnet add package xunit.runner.visualstudio dotnet add package Microsoft.NET.Test.Sdk
Now proceed with creating an xUnit test for the calculator mentioned above. Create a file "CalculatorTests.cs" in "MyApp.Tests" folder.
using Xunit.Framework;
using MyApp;
namespace UnitTestDemo {
public class CalculatorTests {
private readonly Calculator calculator;
public CalculatorTests() {
calculator = new Calculator();
}
[Fact]
public void Add_ShouldReturnSumOfTwoNumbers() {
int result = calculator.Add(5, 3);
Assert.Equal(8, result);
}
[Fact]
public void Subtract_ShouldReturnDifferenceOfTwoNumbers() {
int result = calculator.Subtract(10, 4);
Assert.Equal(6, result);
}
}
}
Unit Testing with MSTest
MSTest is specifically designed for unit testing, allowing developers to test individual components or "units" of code.
MSTest is a Microsoft testing framework for the .NET applications. It provides the tools and infrastructure necessary to create, organize, and execute automated tests to ensure the correctness and reliability of your code.
To perform the MSTest test in your project, first install the MSTest framework in your test project. Using the below command.
dotnet add package MSTest.TestFramework dotnet add package MSTest.TestAdapter dotnet add package Microsoft.NET.Test.Sdk
Now proceed with creating an MSTest test for the calculator mentioned above. Create a file "CalculatorTests.cs" in "MyApp.Tests" folder.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyApp;
namespace UnitTestDemo {
[TestClass]
public class CalculatorTests {
private Calculator calculator;
[TestInitialize]
public void Setup(){
calculator = new Calculator();
}
[TestMethod]
public void Add_ShouldReturnSumOfTwoNumbers() {
int result = calculator.Add(5, 3);
Assert.AreEqual(8, result);
}
[TestMethod]
public void Subtract_ShouldReturnDifferenceOfTwoNumbers() {
int result = calculator.Subtract(10, 4);
Assert.AreEqual(6, result);
}
}
}
Conclusion
Unit testing is a software testing technique that allows developers to verify whether individual components of their project are working as expected. In C#, three major testing frameworks NUnit, xUnit, and MSTest provide tools for writing and executing automated tests and helps developers to ensure that their code is reliable, maintainable, and produces the expected results.