Search code examples
javajunitjunit4

Retry Junit test in java with different parameter


I have Junit test that execute code with parameter, I want in case of assertion fail to retry once again with another parameter. For Example

@Test
public void test1() {
    boolean res = somelogic(3);
    assertTrue(res);
    // just if false I want to run again :
    boolean res = somelogic(4);
    assertTrue(res);    
}

Thanks in advance


Solution

  • You can take advantage of the fact that Java supports short circuit evaluation and write your test as:

    @Test
    public void test1() {
        assertTrue(somelogic(3) || somelogic(4));
    }
    

    That way if somelogic(3) is false, then and only then somelogic(4) will be run to determine the real value of the assertion.