【问题标题】:organising junit tests that expect an exception组织期望异常的junit测试
【发布时间】:2013-08-31 08:05:56
【问题描述】:

我有一个内部使用二维数组的类,并公开了一个 processItem(int i,int j) 方法,如下所示。该方法使用基于 1 的索引并具有一个构造函数,该构造函数将一个 int 值(例如 N)作为 2D 数组大小。因此,对于 N=10,i 和 j 的值应该是 1 到 N 。如果在 i 或 j 小于 1 或大于 10 时调用该方法,该方法将抛出 IndexOutOfBoundsException 。

在我的单元测试中,我想用 i,j 值调用方法

(0,4),(11,3),(3,0),(3,11)

这些调用应该抛出 IndexOutOfBoundsException

我如何组织测试,我必须为每个 i,j 对编写 1 个单独的测试吗?还是有更好的组织方式?

class MyTest{
  MyTestObj testobj;
  public MyTest(){
      testobj = new MyTestObj(10);
  }
  @Test(expected=IndexOutOfBoundsException.class)
  public void test1(){
      testobj.processItem(0,4);
  }

  @Test(expected=IndexOutOfBoundsException.class)
  public void test2(){
      testobj.processItem(11,3);
  }

  @Test(expected=IndexOutOfBoundsException.class)
  public void test3(){
      testobj.processItem(3,0);
  }

  @Test(expected=IndexOutOfBoundsException.class)
  public void test4(){
      testobj.processItem(3,11);
  }
..
}

【问题讨论】:

    标签: java unit-testing junit4


    【解决方案1】:

    如果它们完全独立,则编写独立的测试,但如果它们密切相关(看起来如此),则只需对四个调用进行一个测试,每个调用都包含在 try-catch 中,然后是 fail('exception expected')每次通话。正如在junit 3中所做的那样。

    【讨论】:

      【解决方案2】:

      而不是创建单独的方法来为您的测试方法指定单独的参数。使用JUnit Parameterized Test。这是斐波那契数列的示例。

      因此,您将能够在您的实现中使用它,并期望 ArrayIndexOutOfBounds 用于单一测试方法。

      @RunWith(Parameterized.class)
      public class FibonacciTest {
          @Parameters
          public static Collection<Object[]> data() {
              return Arrays.asList(new Object[][] {
                      Fibonacci,
                      { { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 },
                              { 6, 8 } } });
          }
      
          private int fInput;
      
          private int fExpected;
      
          public FibonacciTest(int input, int expected) {
              fInput= input;
              fExpected= expected;
          }
      
          @Test
          public void test() {
              assertEquals(fExpected, Fibonacci.compute(fInput));
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2012-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-28
        • 1970-01-01
        • 2011-05-28
        • 2017-07-11
        相关资源
        最近更新 更多