How to write the correct unit test for ClassNotFoundExceptions?

I want to test a method in which the following lines appear:

try (Connection connection = dataSource.getConnection()) {
        ((org.postgresql.PGConnection) connection).addDataType("geometry", Class.forName("org.postgis.PGgeometry"));
        ((org.postgresql.PGConnection) connection).addDataType("box3d", Class.forName("org.postgis.PGbox3d"));

        try (Statement statement = connection.createStatement()) {
            /*
             * 4326 is the ID of a format in which the longitude and latitude values should be
             * retreived.
             */
            String sqlQuery = "SELECT ST_Transform(way, 4326) FROM planet_osm_line WHERE (highway='footway' OR highway='steps');";
            ResultSet resultSet = statement.executeQuery(sqlQuery);

            while (resultSet.next()) {
                PGgeometry geom = (PGgeometry) resultSet.getObject(1);
                LineString line = (LineString) geom.getGeometry();
                Point[] wayPoints = line.getPoints();

                pointList.add(wayPoints);
            }
        }
    } catch (SQLException | ClassNotFoundException e) {
        throw new OpenStreetMapDAOException(e.getMessage(), e);
    }

these lines make me catch a ClassNotFoundException, i.e. the challenge Class.forName("name")does it.

The case catchfor is ClassNotFoundExceptionnever achieved in my tests, since these classes are always present. Is there any way to check my block catch?

+4
source share
2 answers

I reorganized the code from my question until I finished the next method for the critical part, i.e. those Class.forName("some.class.name")challenges:

Statement createStatement() throws SQLException, ClassNotFoundException {
    Connection connection = dataSource.getConnection();

    ((org.postgresql.PGConnection) connection).addDataType("geometry", Class.forName("org.postgis.PGgeometry"));
    ((org.postgresql.PGConnection) connection).addDataType("box3d", Class.forName("org.postgis.PGbox3d"));

    return connection.createStatement();
}

In my unit tests, I then used

when(dao.createStatement()).thenThrow(ClassNotFoundException.class);

who finally solved my problem.

0
source

org.postgresql.PGConnection , Mockito .

org.postgresql.PGConnection connection = Mockito.mock(org.postgresql.PGConnection.class)
Mockito.doThrow( ...your exception here...).when( connection ).addDataType("geometry", Class.forName("org.postgis.PGgeometry"));

, . mock- , .

+1

Source: https://habr.com/ru/post/1599315/


All Articles