0

是否可以根据 @Parameters 方法的参数更改断言行为。

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

是否可以完全按照我们定义参数的方式定义断言行为?

提前致谢。

4

2 回答 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(...);
}
于 2012-09-11T10:39:02.133 回答
0

最近我开始了zohhak项目。它让你写

@TestWith({
    "1, true",
    "2, false"
})
public void test(int value, boolean expectedResult) {
  assertThat(...).isEqualTo(expectedResult);
}
于 2012-12-05T16:02:20.990 回答