Junit 使用@Test和expected

Junit 使用@Test和expected,junit,junit4,Junit,Junit4,在我的Junit测试中,只有当被测试对象抛出IOexception时,我的测试用例才必须失败 所以,如果我的测试对象抛出IllegalStateException(或其他错误或异常),那么我的测试用例是正常的,但是如果我的测试对象抛出IOexception,那么我的测试用例一定是失败的 我怎么做 谢谢大家。由于您希望在异常不是IOException时失败,您可以通过捕获IOException并使用fail()进行断言,如下所示: @Test public void yourTestScenari

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

所以,如果我的测试对象抛出IllegalStateException(或其他错误或异常),那么我的测试用例是正常的,但是如果我的测试对象抛出IOexception,那么我的测试用例一定是失败的

我怎么做


谢谢大家。

由于您希望在异常不是IOException时失败,您可以通过捕获
IOException
并使用
fail()
进行断言,如下所示:

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

由于您希望在异常不是IOException时失败,因此可以通过捕获
IOException
并使用
fail()
进行断言,如下所示:

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

您可以使用预期的异常规则

@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();
}

您可以使用预期的异常规则

@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();
}

你能展示你的代码吗?你能展示你的代码吗?这是一个反模式。您可以使用JUnit或AssertJ来验证抛出的异常。您问得清楚吗?他想要一个非IOException条件,而不是预期条件,并且他想要用一种方法处理这两个条件。请参阅我建议的答案。在测试方法中使用try/catch很有诱惑力,但这可能不是最好的答案。这是一种反模式。您可以使用JUnit或AssertJ来验证抛出的异常。您问得清楚吗?他想要一个非IOException条件,而不是预期条件,并且他想要用一种方法处理这两个条件。请参阅我建议的答案。在测试方法中使用try/catch很有诱惑力,但这可能不是最好的答案。我知道这一点,但我们使用这种方法的优势是什么,所以我更喜欢我的方法,因为它看起来很简单?我认为这是完全基于观点的,我们可以采用任何一种方法。看起来你是在试图开始争论。上面使用了测试框架。使用try/catch的替代方案往往在测试框架之外工作。我更倾向于使用AssertJ,因为这两种方法都能做到最好。我知道这一点,但使用这种方法有什么好处,所以我更喜欢我的方法,因为它看起来很简单?我认为这是完全基于观点的,我们可以采用任何一种方法。看起来你是在试图开始争论。上面使用了测试框架。使用try/catch的替代方案往往在测试框架之外工作。我更倾向于使用AssertJ,这样您就可以两全其美。