Ruthlessly Helpful

Stephen Ritchie's offerings of ruthlessly helpful software engineering practices.

The Prime Directive

When creating test cases, I find that using prime numbers helps avoid coincidental arithmetic issues and helps make debugging easier.

A common coincidental arithmetic problem occurs when a test uses the number 2. These three expressions: 2 + 2, 2 * 2, and System.Math.Pow(2, 2) are all equal to 4. When using the number 2 as a test value, there are many ways the test falsely passes. Arithmetic errors are less likely to yield an improper result when the test values are different prime numbers.

Consider a loan that has a principal of $12,000.00, a term of 360 payments, an annual interest rate of 12%, and, of course, don’t forget that there are 12 months in a year. Because the coincidental factor is 12 in all these numbers, this data scenario is a very poor choice as a test case.

In this code listing, the data-driven test cases use prime numbers and prime-derived variations to create uniqueness.

[TestCase(7499, 1.79, 0, 72.16)]
[TestCase(7499, 1.79, -1, 72.16)]
[TestCase(7499, 1.79, -73, 72.16)]
[TestCase(7499, 1.79, int.MinValue, 72.16)]
[TestCase(7499, 1.79, 361, 72.16)]
[TestCase(7499, 1.79, 2039, 72.16)]
[TestCase(7499, 1.79, int.MaxValue, 72.16)]
public void ComputePayment_WithInvalidTermInMonths_ExpectArgumentOutOfRangeException(
    decimal principal,
    decimal annualPercentageRate,
    int termInMonths,
    decimal expectedPaymentPerPeriod)
    // Arrange
    var loan =
        new Loan
                Principal = principal,
                AnnualPercentageRate = annualPercentageRate,

    // Act
    TestDelegate act = () => loan.ComputePayment(termInMonths);

    // Assert

Here’s a text file that lists the first 1000 prime numbers:

Here’s a handy prime number next-lowest/next-highest calculator:

Also, I find that it’s often helpful to avoid using arbitrary, hardcoded strings. When the content in the string is unimportant, I use Guid.NewGuid.ToString(), or I write a test helper method like TestHelper.BuidString() to create random, unique strings. This helps avoid same-string coincidences.

Leave a Reply


You are commenting using your account. Log Out /  Change )

Google photo


Twitter picture


Facebook photo


Connecting to %s

%d bloggers like this: