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
Assert.Throws<ArgumentOutOfRangeException>(act);
}

Here’s a text file that lists the first 1000 prime numbers: http://primes.utm.edu/lists/small/1000.txt

Here’s a handy prime number next-lowest/next-highest calculator: http://easycalculation.com/prime-number.php

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.

### Like this:

Like Loading...

*Related*