Lesson Sunday

Debugging code can be both frustrating and challenging. In this lesson, we'll cover a few tools we can use to pinpoint errors in our tests.

Debugging in MSTest


Let's take another look at our Leap Year project. This version has an added bug. Here's our new code:

...
    public bool IsLeapYear(int year)
    {
      if (year % 400 == 0)
      {
        return true;
      }
      else if (year % 100 == 0) {
        return false;
      }
      else
      {
        return year % .4 == 0;
      }
    }
...

Let's run our tests:

Starting test execution, please wait...
Failed   IsLeapYear_NumberDivisibleByFour_True
Error Message:
 Assert.AreEqual failed. Expected:<True>. Actual:<False>.
Stack Trace:
   at Calendar.Tests.LeapYearTests.IsLeapYear_NumberDivisibleByFour_True() in /Users/epicodus_staff/Desktop/Calendar.Solution/Calendar.Tests/ModelTests/LeapYearTests.cs:line 13


Total tests: 4. Passed: 3. Failed: 1. Skipped: 0.
Test Run Failed.
Test execution time: 1.3841 Seconds

According to the error message, the Assert.AreEqual() method has failed. Our expected output true isn't equivalent to the actual output of false.

There is also a stack trace. This is an active report of our program as it runs. It also contains helpful information to quickly track bugs. The stack trace can usually pinpoint the exact line that is causing the bug.

In this case, our stack traces states that the error is at line 13 of the LeapYearTests.cs file. If we take a look at that line in our test file, we'll see exactly which test failed.

Reading Failure Messages

Thankfully, the error message gives us a few indications to where the error can be found. It's really important to gain practice deciphering error messages like these. Let's look carefully at the message we received above:

  • The line reading Failed IsLeapYear_NumberDivisibleByFour_True tells us which of our tests failed. In this case, it’s the test IsLeapYear_NumberDivisibleByFour_True().

  • Below that in the error message section, it tells us what the Expected result was (True, in our case), and the Actual result it received instead (False, in this example).

  • The next section provides a stack trace of what caused the error, and where. Stack traces are useful for figuring out what has caused a bug in your code. They can vary in size, and sometimes contain huge amounts of information. They may be intimidating at first, but the most useful line is usually the one on top. In our case it’s stating the error occurred in Line 13. If we check our code, we can see this is the line containing our Assert.AreEqual() statement. So, the test failed because the arguments provided to Assert.AreEqual() were not actually equal.

Lesson 9 of 20
Last updated April 14, 2022