Unit Testing

Let's discuss unit testing.

What are unit tests?

Unit tests verify that the logic of code is working as expected. Unit testing breaks a program down into small, testable, individual units.

Why use unit tests?

For example, if we want to test a console-based application that has the following code:

namespace UTCalculator {
    public class CalculatorFeatures
    {
        public static int AddTwoNumbers(int num1, int num2)
        {
            int result = num1 - num2;
            return result; 
        } 
    }
}

Note: We have to test a method named AddTwoNumbers in the class named CalculatorFeature.

If we call this method now, it won’t provide us with the correct output.

Press + to interact
Console.WriteLine(UTCalculator.CalculatorFeatures.AddTwoNumbers(10, 4)); // Output: 6
namespace UTCalculator {
public class CalculatorFeatures
{
public static int AddTwoNumbers(int num1, int num2)
{
int result = num1 - num2;
return result; }
}
}

The code above runs because there are no syntax errors in it. There’s a logic error, however (10 + 4 should equal 14, not 6). A unit test is added to catch this type of error.

How to write a unit test

Use the following steps to write a unit test.

Step 1:

Make a testing directory. In this example, we’re creating a directory named CalculatorTest in the parent directory of UTCalculator ...