문제

I have this unit test, that the overall test fails because of the exceptions that is thrown, although its expected:

@Test(expected = AutoGenerateStringIdException.class)
public void testPut_shouldThrowException(){
    RootEntity rootObject = new RootEntity(); 
    // Some codes here
    try {
        Key key = store.put(rootObject);
    } catch(AutoGenerateStringIdException e){
        assertEquals(e.getMessage(), "Cannot auto-generate String @Id"); 
    }
}
도움이 되었습니까?

해결책 2

Please have a look at the JUnit wiki: https://github.com/junit-team/junit/wiki/Exception-testing It lists different approaches for testing exceptions.

다른 팁

You can either have @Test(expected = SomeException.class) or use a try...catch as you're doing. You can't use both of them at the same time.

When you declare a test to expect a certain exception to be thrown and if you catch it within the test, it wouldn't be thrown, would it?

Although I haven't tried it, you could try re-throwing the exception from the catch block.

catch(AutoGenerateStringIdException e){
    assertEquals(e.getMessage(), "Cannot auto-generate String @Id"); 
    throw e;
}

If exception is expected in test, you should not catch it. Just remove try/catch and watch, what happens.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top