how do you test simple if else statements with J-unit?

245 views Asked by At

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;
    }
}
1

There are 1 answers

1
alexbt On

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));
}