使用@Test和预期

时间:2016-11-01 13:41:44

标签: junit junit4

在我的Junit测试中,我有一个测试用例,只有当IOexception被我的测试对象抛出时才必须失败。

因此,如果我的测试对象抛出IllegalStateException(或其他错误或异常),我的测试用例就可以,但如果我的测试对象抛出IOexception,我的测试用例必定是失败的。

我该怎么做?

谢谢大家。

2 个答案:

答案 0 :(得分:0)

如果您想在异常不是IOException时失败,您可以通过捕获IOException并使用fail()断言来执行此操作,如下所示:

@Test
public void yourTestScenario() {
    try { 
      //code that throws IOException and other Exceptions
    } catch(IOException ioexe) {
        Assert.fail();
    } catch(Exception exe) {
       //Ignore
    } 
}

答案 1 :(得分:0)

您可以使用预期的例外规则

@Rule
public ExpectedException expected = new ExpectedException();


@Test
public void doSomethingWithNoIOException() {
    // we expect an exception that's NOT an instance of IOException
    // you'll need to static import the hamcrest matchers referenced below
    expected.expect(not(instanceOf(IOException.class));

    // call the method under test
    callSomething();
}