【问题标题】:Assert that certain parameterized vectors will throw an exception in JUnit?断言某些参数化向量会在 JUnit 中引发异常?
【发布时间】:2014-11-10 22:33:50
【问题描述】:

我想知道如何为特定的异常断言编写测试?

例如(我的测试数据容器):

@Parameters(name = "{index}: {0} > {1} > {2} > {3} > {4}")
public static Iterable<Object[]> data() {
  return Arrays.asList(new Object[][] {
    {"1200", new byte[] {0x4B0}, "1200", 16, 2},
    {"10", new byte[] {0x0A}, "10", 8, 1},
    {"13544k0", new byte[] {0x0A}, "1200", 8, 1},  <== assert thrown exception
    {"132111115516", new byte[] {0x0A}, "1200", 8, 1},<== assert thrown exception
  });
}

是否可以使用这样的容器数据来断言异常,或者我需要在具体的测试方法中建模情况?

【问题讨论】:

  • 你在测试什么?

标签: java unit-testing exception junit parameterized


【解决方案1】:

在 JUnit 4.7 之前,不可能像这样使用数据驱动测试,其中一些数据组合会产生异常,而另一些则不会。

可以创建两个不同的数据驱动测试,其中一个中的所有组合都不会产生异常,而另一个中的所有组合都会产生异常。

除非您需要额外的测试逻辑,否则将@Test(expected=YourException.class) 用于预期异常的测试。 expected 注解参数不是很强大。

自 4.7 以来,有一个适用于它的 @Rule。有关详细信息,请参阅@eee 的答案。

【讨论】:

  • @KostyaKrivomaz 请参阅以下来自 eee 的答案。当然可以实现您想要的。
【解决方案2】:

您可以为此使用 JUnit 规则 ExpectedException,这是一个可运行的示例:

@RunWith(Parameterized.class)
public class MyParameterizedTest {

    public class UnderTest {
        public void execute(String input) {
            if ("1".equals(input)) {
                throw new RuntimeException();
            }
        }
    }

    @Rule
    public ExpectedException expected = ExpectedException.none();

    @Parameters(name = "{index}: {0}")
    public static Iterable<Object[]> data() {
        return Arrays.asList(new Object[][] {
                    {"1", RuntimeException.class},
                    {"2", null}    
        });
    }

    @Parameter(value = 0)
    public String input;

    @Parameter(value = 1)
    public Class<Throwable> exceptionClass;

    @Test
    public void test() {
        if (exceptionClass != null) {
            expected.expect(exceptionClass);
        }

        UnderTest underTest = new UnderTest();          
        underTest.execute(input);
    }
}

【讨论】:

    【解决方案3】:

    不要这样做。你怎么知道你的代码应该在什么时候抛出异常?将此数据集分成两组。一个正确通过,第二个抛出异常。然后创建 2 个测试 - 一个总是期待异常,另一个期待没有异常

    您可以通过添加额外的参数(如所示的@eee)来组合这两种情况,但它会为您的测试用例增加逻辑/复杂性并降低它们的可读性

    【讨论】:

      猜你喜欢
      • 2010-09-14
      • 2019-01-28
      • 1970-01-01
      • 2012-04-07
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多