1

I have this if-else statement and I want to write a J unit test that will test each individual line to see is correct. Any ideas?

public class Testings {

    public static int computeValue(int x, int y, int z) {
        int value = 0;

        if ( x == y ) 
            value = x + 1;
        else if (( x > y) && ( z == 0))
            value = y + 2;
        else
            value = z;

        return value;
    }
}
Boris Schegolev
  • 3,601
  • 5
  • 21
  • 34
  • maybe you explain how detailed it should be tested? - only with single numbers, test clusters, etc – wake-0 Dec 27 '16 at 07:29

1 Answers1

0

Test your method with the values that cover all cases:

  • x == y
  • x != y and x > y and z == 0
  • x != y and x > y and z != 0
  • x != y and x < y and z == 0
  • x != y and x < y and z != 0
  • x == y and z != 0
  • x == y and z == 0

Example:

assertEquals(4, Testings.computeValue(3, 3, 10)); // x == y
assertEquals(7, Testings.computeValue(10, 5, 0)); // x != y and x > y and z == 0
assertEquals(1, Testings.computeValue(10, 5, 1)); // x != y and x > y and z != 0
...

Also, you should have one assert per test method so you can give it a proper name:

@Test
public void testXEqualY(){
    int x=3, y=3, z=10;
    assertEquals(4, Testings.computeValue(x, y, z));
}
alexbt
  • 16,415
  • 6
  • 78
  • 87
  • geez! I just realized this is a few weeks old, probably not useful anymore! Anyhow, here it is :) – alexbt Jan 19 '17 at 03:24