java - How to write a proper unit test for ClassNotFoundExceptions? -
i want test method 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 id of format in longitude , latitude values should * retreived. */ string sqlquery = "select st_transform(way, 4326) planet_osm_line (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); }
those lines force me catch classnotfoundexception
, i.e. call of class.forname("name")
so.
the catch
case classnotfoundexception
never reached in tests since these classes present. is there way test catch
block?
as org.postgresql.pgconnection
seems interface, try mock via mockito or similar mocking framework.
org.postgresql.pgconnection connection = mockito.mock(org.postgresql.pgconnection.class) mockito.dothrow( ...your exception here...).when( connection ).adddatatype("geometry", class.forname("org.postgis.pggeometry"));
with these 2 lines creating mock object connection can use in method. mock object throw given exception when method called these parameters.
Comments
Post a Comment