Wednesday, April 20, 2016

Parameterized JUnit Tests

JUnitParams provides a runner - JUnitParamsRunner, to add parameterized tests in a test class. With this runner parameterized and non-parameterized test methods can be combined in the same class.

  1. @RunWith(JUnitParamsRunner.class)  
  2. public class ParameterizedTests {  
  3.     @Parameters({"1, true""2, false"})  
  4.     @Test  
  5.     public void test1(int num, boolean result) {  
  6.         assertThat(num == 1, is(result));  
  7.     }  
  8. }  
@RunWith(JUnitParamsRunner.class)
public class ParameterizedTests {
    @Parameters({"1, true", "2, false"})
    @Test
    public void test1(int num, boolean result) {
        assertThat(num == 1, is(result));
    }
}
To pass in objects or null values, a separate method can be setup, which then can be added to the @Parameters annotation.
  1. @RunWith(JUnitParamsRunner.class)  
  2. public class ParameterizedTests {  
  3.     private Object[] params() {  
  4.         return $(  
  5.                 $(1true),  
  6.                 $(2false)  
  7.         );  
  8.     }  
  9.   
  10.     @Parameters(method = "params")  
  11.     @Test  
  12.     public void test1(int num, boolean result) {  
  13.         assertThat(num == 1, is(result));  
  14.     }  
  15. }  
@RunWith(JUnitParamsRunner.class)
public class ParameterizedTests {
    private Object[] params() {
        return $(
                $(1, true),
                $(2, false)
        );
    }

    @Parameters(method = "params")
    @Test
    public void test1(int num, boolean result) {
        assertThat(num == 1, is(result));
    }
}

No comments: