Skip to content

Unit 2 ‐ Lesson 2

Robert Millikin edited this page Jul 28, 2020 · 4 revisions

Unit tests

A critically important and relatively recently popularized (~1990s) tool in debugging is the unit test. A unit test is code that tests a unit (a very small region) of your program. For example, you may test the factorial operation of your calculator program by inputting 4 and expecting to see 24 as a result. If you put in 4 and get out 24, presumably the factorial operation is working correctly; if a different value is returned, then the factorial operation has a bug in it.

Unit tests perform this workflow automatically - input, output, and checking to see if the actual output matches the expected output. Unit tests are essential in large, constantly-changing projects. If you or another developer on your team changes or adds a section of code, unit tests ensure that the new code (and related code) meets the expected output.

Unit tests are extremely valuable because they prevent future bugs.

Unit tests are usually designed to take a few milliseconds to run, and a project can end up having hundreds of unit tests. This is a good thing - it means lots of diverse areas of your code are constantly tested for deviations from expected results, ensuring stability, accuracy, and usability of your program. It also improves your team's efficiency because you are not constantly manually testing for and fixing the same bugs repeatedly. Remember, the point of programming is to make the computer do the work for you - that includes debugging.

The code that is tested by unit tests is called covered code or covered lines; the percentage of covered code in a program is an important metric of code quality. 100% coverage is ideal.

Writing a unit test

Let's write a unit test. We will first need to create a unit test project. Technically, Visual Studio organizes your code into a solution first, and a solution can have multiple projects. You can view the solution's files in the solution explorer - usually on the right-hand side. You can ensure the solution explorer is open by going to View -> Solution Explorer. Now we will create a new unit test project; right-click on Solution 'ConsoleCalculator' -> Add -> New Project -> NUnit Test Project (.NET Core) and name the project Test. Click Create. This uses a library (a collection of code [methods, etc.] that someone else published) called NUnit, which allows you to create unit tests that integrate with Visual Studio easily.

You should now see two methods in a new file; one method is called Setup and the other is called Test1.

Side note: Visual Studio should automatically download and install NUnit, but if it doesn't, you'll see some red underlining in the new file. Mouse over the red underlining, right click, go to Install Package 'NUnit' -> Find and install latest version.

The Setup method has a [SetUp] tag before it, and Test1 has a [Test] tag before it. These tags are used by NUnit to define a unit test. The [SetUp] tag tells the compiler to run the tagged method before each unit test runs. The [Test] tag defines a unit test. Ignore these two methods for now and after the Test1 method ends (after its curly bracket) press enter and add a new test by typing [Test] and then public void TestFactorial(). Add curly brackets to define the beginning and end of your method.

Before we write the body of our unit test, we need to do some extra work because we want to reference code across projects (i.e., we want to use ConsoleCalculator methods defined in our unit test project). First, add a reference to ConsoleCalculator by right-clicking the Test project in the solution explorer, then going to Add -> Reference -> Check the box for ConsoleCalculator then click OK. Now we must also change our ConsoleCalculator code a little bit; go back to that file by double-clicking the Program.cs file within the ConsoleCalculator project in the solution explorer. Add the keyword public before class Program, and again add public before the static int Factorial method (i.e., public static int Factorial). We will discuss public in more detail in the next few lessons.

Now we are ready to write the unit test - go back to the UnitTest1.cs file. Inside the TestFactorial() method, create an int variable called input and an int variable called expectedOutput; select appropriate values, e.g. 4 and 24, for the respective variables. You can call the factorial method in ConsoleCalculator by typing ConsoleCalculator.Program.Factorial(). This syntax tells the compiler that you want to reference a method called Factorial which is part of the Program class (discussed later), which is part of the ConsoleCalculator project.

[Test]
public void TestFactorial()
{
   int input = 4;
   int expectedOutput = 24;

   int output = ConsoleCalculator.Program.Factorial(input);

   Assert.That(output == expectedOutput);
}

Now we will run the unit test. The Test Explorer may be visible (usually on the left side) but if it's not, go to Test -> Test Explorer. Expand the arrows until you find the TestFactorial test; right click it and select Run. After a few seconds your unit test should pass (it will show a green checkmark next to the test). You can also click Debug instead of Run, which will allow you to use breakpoints to stop the code at places of your choosing, though it is slightly slower.

Homework 5

Calculator - Part 5

  • Write several unit tests, one for each of your calculator's operations (addition, subtraction, multiplication, etc.). Make sure the unit tests pass.