For example, if I have something like this:
try {
// db call
} catch ( Exception e ) {
return false
}
I want to write a unit test to test this method. How should I write that? Or to say it differently, what will be an example of code that will cause SQLException or any other exception to be thrown?
We usually write such a test code like this:
try {
// Do something you expect to fail.
Assert.fail();
} catch (SQLException e) { // Expected exception type.
Assert.assertEquals(e.getMessage(), "Expected message");
// Or alternatively.
Assert.assertTrue(e.getMessage().startsWith("Expected start of the message"));
}
The Assert.fail() part makes sure that the test fails in case the code did not throw the error.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.