Introduction
Unit testing is a crucial part of software development that helps ensure the quality and reliability of code. Unit tests are automated tests that check individual units or components of code to verify that they are working as expected. In C# and other .NET languages, several testing frameworks are available, including NUnit, xUnit.net, and MSTest. This article will focus on using MSTest to write and run unit tests for C# code.
Prerequisites
Before we start, make sure you have the following tools and software installed:
- Microsoft Visual Studio (2017 or later) or Visual Studio Code
- .NET Core SDK (version 2.1 or later)
Getting Started
To create a new C# project with unit testing support, follow these steps:
1. Open Visual Studio and create a new project using the "Class Library (.NET Standard)" template.
2. Open Console Application
3. Configure our Project
Then see our Home Screen
4. Add our home screen static main
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
Employee objEmployee = new Employee();
Console.WriteLine(objEmployee.GetName("Guna","Palai"));
}
}
5. Create New Class and add a method like this:-
namespace TestingMethod
{
public class Employee
{
public string GetName(string firstName, string lastName)
{
return string.Concat(firstName, " ", lastName);
}
}
}
To write your unit test, follow these steps
Add your Test Project
Add a new class in our MStest project
namespace UnittestMS
{
[TestClass]
public class UnitTest
{
[TestMethod]
public void GetNameTest()
{
//Arrange
Employee objEmployee = new Employee();
String firstName = "Guna";
String lastName = "Palani";
String expected = "Guna Palani";
String actual;
//Act
actual = objEmployee.GetName(firstName, lastName);
//Assert
Assert.AreEqual(expected, actual);
}
}
}
-
In the "Arrange" section, set up any objects or data your test method needs.
-
In the "Act" section, perform the action you want to test, such as calling a method or calculation.
-
In the "Assert" section, verify that the actual result of the action matches the expected result.
-
Save the file.
Running Your Unit Test
1. Right-click our method and click Run test or click Ctrl+R, T
See our Output Screen test Explorer
Conclusion
Unit testing is an integral part of software development that can help you catch bugs early and ensure the quality and reliability of your code. This article covered the basics of unit testing in C# using the MSTest framework. We looked at creating a new C# console project with unit testing support, writing a simple unit test, and running the test using the Test Explorer window. With MSTest, it's easy to get started with unit testing in C#.please use the comment section if you have any doubts.