Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make DB fail deterministically for testing

Tags:

java

testing

I have a Java application that uses lots of java.sql.Connection to a database.

I want to test that, if the database is unavailable, my services return the appropriate error codes (distinguishing between temporary and permanent problems e.g. HTTP 500 and 503).

For testing, my application connects to an embedded, local, in-memory h2 database; the application is not aware of this, only my integration test is.

How can I make writes to the database fail deterministically, e.g. hook into commits and make them throw a custom SQLException? I want a global 'database is unavailable' boolean in the test code that affects all connections and makes my application exercise its reconnect logic.

(I had started by proxying Connection and putting an if(failFlag) throw new MySimulateFailureException() in commit(); but this didn't catch PreparedStatement.executeUpdate(); before I embark on proxying the PreparedStatement too - its a lot of methods! - I'd like to be taught a better way...)

like image 377
Will Avatar asked Nov 13 '22 19:11

Will


1 Answers

I think this is a good candidate for using aspects. With eg. Spring it is supremely easy to pointcut entire packages or just certain methods that you wish to fail - specifically you could have a before advice always throwing a ConnectException or do something more advanced with the around advice.

Cheers,

like image 194
Anders R. Bystrup Avatar answered Nov 15 '22 11:11

Anders R. Bystrup