1

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.

2 Answers 2

4

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 Runnables.

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(...);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I think this should help.
Thanks, this is exactly what I was looking for. It worked very well for me. :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.