I'm writing a jUnit test for a calculation function
double calculate(double val1, double val2);
The function is expected to return the same result if the inputs are "flipped", i.e. it shouldn't matter which one comes first, and it shouldn't matter if they are negative or positive (as long as they have equal signs).
The following should all produce the same result:
calculate(1.5, 4.7);
calculate(4.7, 1.5);
calculate(-1.5, -4.7);
calculate(-4.7, -1.5);
but this has the disadvantage of terminating the test method when one of them fails.
My current test simply makes 4 separate assertions:
assertEquals( 9.472, result1, 0.001 );
assertEquals( 9.472, result2, 0.001 );
assertEquals( 9.472, result3, 0.001 );
assertEquals( 9.472, result4, 0.001 );
but this has the disadvantage of terminating the test method when one of them fails. The same goes for testing using an array:
assertArrayEquals(
new double[]{9.472, 9.472, 9.472, 9.472},
new double[]{result1, result2, result3, result4},
0.001);
Another option I came up with was to simply assert that they are all equal, using
assertTrue( result1 == result2 && result2 == result3 && result3 == result4 );
but that has the disadvantage of not telling you the actual values when it fails.
What is the best way of testing something like this?
This sounds like exactly what parameterized tests are for.
Your test method will just be
@Test
public void testCommutativity() {
assertEquals(calculate(a, b), calculate(b, a), .001);
}
And your parameters method will be something like
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ 1.5, 4.7 }, { -1.5, -4.7 }
});
}
You can even programmatically alter your parameters (make one or both negative) before returning them.