简体   繁体   中英

Change Assert behavior as per different parameters in Parameterized Junit test cases

Is it possible to change the assert behavior as per the parameters of the @Parameters method.

Class abcTest
{
  ..
  @Parameters
  public static Collection<Object[]> testParameters()
  {
        return Arrays.asList(new Object[][] {
        {1},{2} 
        });
  }

  ..
  @Test
  public void test()
  {
    ...
    if(num == 1) { assertTrue(..); }
    if(num == 2) { assertFalse(..); }
    ...
  }
}

is it possible to define the assert behavior exactly the way we define parameters?

Thanks in advance.

In the simplest case you can pass expected values as parameters and use them in assertions, as shown in javadoc .

In more complex cases you need to encapsulate assert logic into objects and pass them as parameters.

If you need different assertions for the same values you can use assertThat() and Matcher<T> :

class abcTest
{
  @Parameters
  public static Collection<Object[]> testParameters()
  {
        return Arrays.asList(new Object[][] {
            {1, CoreMatchers.is(true)},
            {2, CoreMatchers.is(false)} 
        });
  }

  ..
  @Test
  public void test()
  {
      ...
      assertThat(value, matcher);
  }
}

Otherwise, if different parameters need completely different assertions you can pass them as Runnable s.

However, it may be not a good idea to use parameterized tests in this case - if you need completely different assertions for different cases it can be more elegant to create separate test methods for these cases, extracting their commons parts into helper methods:

@Test
public void shouldHandleCase1() {
   handleCase(1);
   assertTrue(...);
}

@Test
public void shouldHandleCase2() {
   handleCase(2);
   assertFalse(...);
}

recently I started zohhak project. it let's you write

@TestWith({
    "1, true",
    "2, false"
})
public void test(int value, boolean expectedResult) {
  assertThat(...).isEqualTo(expectedResult);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM