Please have a look at the JUnit wiki: https://github.com/junit-team/junit/wiki/Exception-testing It lists different approaches for testing exceptions.
Test fails because of Exception thrown
题
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
其他提示
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.
不隶属于 StackOverflow