简体   繁体   English

根据参数化Junit测试用例中的不同参数更改声明行为

[英]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. 是否可以根据@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(..); }
    ...
  }
}

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 . 在最简单的情况下,您可以将期望值作为参数传递,并在断言中使用它们,如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> : 如果您需要对相同值使用不同的断言,则可以使用assertThat()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. 否则,如果不同的参数需要完全不同的断言,则可以将它们作为Runnable传递。

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. 最近我开始了zohhak项目。 it let's you write 它让你写

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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