Chapter 10. Automate Tests

Keep the bar green to keep the code clean.

The jUnit motto

Guideline:

  • Automate tests for your codebase.

  • Do this by writing automated tests using a test framework.

  • This improves maintainability because automated testing makes development predictable and less risky.

In Chapter 4, we have presented IsValid, a method to check whether bank account numbers comply with a checksum. That method contains a small algorithm that implements the checksum. It is easy to make mistakes in a method like this. That is why probably every programmer in the world at some point has written a little, one-off program to test the behavior of such a method, like so:

using System;
using eu.sig.training.ch04.v1;

namespace eu.sig.training.ch10
{
    public class Program
    {
        [STAThread]
        public static void Main(string[] args)
        {
            string acct;
            do
            {
                Console.WriteLine("Type a bank account number on the next line.");
                acct = Console.ReadLine();
                Console.WriteLine($"Bank account number '{acct}' is" +
                    (Accounts.IsValid(acct) ? "" : " not") + " valid.");
            } while (!String.IsNullOrEmpty(acct));
        }
    }
}

This is a C# class with a Main method, so it can be run from the command line:

C:\> Program.exe
Type a bank account number on the next line.
123456789
Bank account number '123456789' is valid.
Type a bank account number on the next line.
123456788
Bank account number '123456788' is not valid.
C:\>

A program like this can be called a manual unit test. It is a unit test because it is used to test ...

Get Building Maintainable Software, C# Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.