Rishabh Agarwal jain Rishabh Agarwal jain - 3 months ago 16
MySQL Question

Make the JDBC call throw a SQLException for a test case

I am writing test cases for my program and to maximize the code coverage I have to raise a SQLException, that exception will then be checked in my test case.

public double getTotalAmount(String form,String name) {
DbManager manager = new DbManager();
double amount = 0;
ResultSet executeQuery = manager.findAll("select amount From "+form+" where employee_name='"+name+"'");
try {
while (executeQuery.next()) {
String tempAmount = executeQuery.getString("amount");
amount += Double.valueOf(tempAmount);
}
return amount;
} catch (SQLException e) {

e.printStackTrace();
}
manager.closeConnection();
return -1;


Now I am unable to raise the SQLException in my code, can you suggest me how can I raise this exception in my code.

Answer

According to the javadocs

https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getString(int)

SQLException - if the columnIndex is not valid;

so in your code do

String tempAmount = executeQuery.getString(1000);

If your tester class needs to catch this exception, then you will also need to throw it from getTotalAmount