-1

I know I can use Mockito to force an exception throw from DAO methods, but how can I get test coverage inside the DAO class properly?

Example:

public static void addUser(int userId, int groupId)
        throws DataSourceException {
    String query = "INSERT INTO RUserGroup (userId, groupId) VALUES (?, ?)";
    Connection connection = Pool.getInstance().getConnection();
    try (PreparedStatement ps = connection.prepareStatement(query);) {
    // ...
    } catch (SQLException e) {
        throw new DataSourceException(e);
    } finally {
        Pool.getInstance().returnConnection(connection);
    }
}

How can I reach the "throw new DataSourceException(e)"? I have a lot of those cases in the code and they completely ruin branch coverage. I am using JaCoCo for the coverage.

Lomtrur
  • 1
  • 2

1 Answers1

0

The problem is mocking the Pool.getInstance() method, since you want your connection to be a mock, since you could then let it throw exceptions if necessary.
Mockito doesn't let you do that.

For such cases, See Mocking static methods with Mockito

Community
  • 1
  • 1
Koos Gadellaa
  • 1,220
  • 7
  • 17