在JUnit中断言异常

IUn*_*own 3 java junit

我需要编写一个JUnit测试用例,它将测试一个传递不同排列的函数,并得到相应的结果.
成功的用例不返回任何内容,而失败的排列会抛出异常(异常类型无关紧要).

例如.testAppleisSweetAndRed(水果,颜色,味道)
测试会调用以下内容 -

testAppleisSweetAndRed(orange,red,sweet)//throws exception
testAppleisSweetAndRed(apple,green,sweet)//throws exception
testAppleisSweetAndRed(apple,red,sour)//throws exception
testAppleisSweetAndRed(apple,red,sweet)//OK
Run Code Online (Sandbox Code Playgroud)

如果调用的行为符合预期,则测试成功.
断言如何捕获前3次调用以确保它们确实引发预期的异常?

Job*_*eph 6

如果您使用的是JUnit 4或更高版本,则可以按如下方式执行.你可以使用

@Rule
public ExpectedException exceptions = ExpectedException.none();
Run Code Online (Sandbox Code Playgroud)


这提供了许多可用于改进JUnit测试的功能.
如果您看到以下示例,我将在异常上测试3件事.

  1. 抛出的异常类型
  2. 消息例外
  3. 异常的原因


public class MyTest {

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

    ClassUnderTest testClass;

    @Before
    public void setUp() throws Exception {
        testClass = new ClassUnderTest();
    }

    @Test
    public void testAppleisSweetAndRed() throws Exception {

        exceptions.expect(Exception.class);
        exceptions.expectMessage("this is the exception message");
        exceptions.expectCause(Matchers.<Throwable>equalTo(exceptionCause));

        testClass.appleisSweetAndRed(orange,red,sweet);
    }

}
Run Code Online (Sandbox Code Playgroud)


Rah*_*mar 5

告诉您的测试方法您期望形成测试方法的异常类型.你只需要编写如下语法.

@Test(expected = Exception.class) 
Run Code Online (Sandbox Code Playgroud)

这意味着我期待从测试中抛出异常.您可以使用其他异常以及ArrayOutOfBound等.