How to write a JUnit unit test for database call?

771 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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.