Unit Testing in DotNet C#
Testing Frameworks in DotNet
XUint - Most Popular testing framework is xUnit, which is now part of the open source .NET Foundation.
MSTest - MSTest is recently made Microsoft's open sourced test framework.
Unit Testing is to test smallest part of program such as function or method, by using a unit testing framework, the unit tests become a separate entity which can then run automated tests on the program.
Each unit is tested separately before integrating them into modules and to test further.
AAA Pattern for Unit Test in C#
The AAA (Arrange, Act, Assert) pattern is a common way of writing unit tests for a method under test.
The Arrange section of a unit test method initializes objects and sets the value of the data that is passed to the method under test.
The Act section invokes the method under test with the arranged parameters.
The Assert section verifies that the action of the method under test behaves as expected.
To test the SortArray method of our example :
The unit test framework that we use and Visual Studio IntelliSense will help us to write code for our unit tests for a code project and to run the same in Test Explorer.
First we will add UnitTesting project as console application in our solution, will add ArraySort class having simple SortArray method to sort list of strings.
public class ArraySort
{
public string[] SortArray(string[] strArray)
{
if (strArray.Count() == 0)
throw new ArgumentException("Array list is empty.");
Array.Sort(strArray);
return strArray;
}
}
How to define unit test for above method
Next we are going to define test project, go to Solution explorer right click and add new project of type UnitTest and add a name UnitTesting.Test.
To add project dependency go to Solution Explorer > select UnitTesting.Test Project and click on Add Reference and select UnitTesting first project we created, now we can access the methods and classes of our main project.
Here we are going to test two methods TestSortArray() and TestSortArrayEmptyList() to test conditions when list of array is passed or when list is empty, our method in ArraySort class will throw error of ArgumentException type.
[TestMethod]
public void TestSortArray()
{
string[] strArray = new string[] { "d", "b", "c", "a" };
UnitTesting1.ArraySort arraySort = new UnitTesting1.ArraySort();
var result = arraySort.SortArray(strArray);
var sortedArray = new string[] { "a", "b", "c", "d" };
bool isEqual = Enumerable.SequenceEqual(sortedArray, result);
Assert.AreEqual(isEqual, true);
}
[TestMethod]
public void TestSortArrayEmptyList()
{
string[] strArray = new string[] {};
UnitTesting1.ArraySort arraySort = new UnitTesting1.ArraySort();
Exception ex = Assert.ThrowsException<System.ArgumentException>(() => arraySort.SortArray(strArray));
Assert.AreEqual("Array list is empty.", ex.Message);
}