is there way test below code.here connecting database jndi.i new mockito , not getting way test same.
@suppresswarnings("unused") public connection getjndiconnection() { connection result = null; try { initialcontext initialcontext = new initialcontext(); if (initialcontext == null) { logger.info("jndi problem. cannot initialcontext."); } datasource datasource = (datasource) initialcontext.lookup(jndiname); if (datasource != null) { result = datasource.getconnection(); } else { logger.info("failed lookup datasource."); } } catch (namingexception ex) { logger.error("cannot connection: " + ex); } catch (sqlexception ex) { logger.error("cannot connection: " + ex); } return result; }
of course, can it, think should read documentation yourself. main points here is:
initialcontext initialcontext = mock(initialcontext.class); datasource datasource = mock(datasource.class); connection expected = mock(connection.class); whennew(initialcontext.class).withnoarguments().thenreturn(initialcontext); when(initialcontext.lookup(jndiname)).thenreturn(datasource); when(initialcontext.getconnection()).thenreturn(connection); connection result = intatnceofcalss.getjndiconnection(); assertsame("should equals", expected, result);
also should use powermock mock constructors , static methods. have deal logger, add code:
@beforeclass public static void setupclass() { mockstatic(loggerfactory.class); logger logger = mock(logger.class); when(loggerfactory.getlogger(applysqlfileifexistschange.class)).thenreturn(logger); }
don't forget annotations:
@runwith(powermockrunner.class) @preparefortest({loggerfactory.class})
try read doc http://site.mockito.org/mockito/docs/current/org/mockito/mockito.html
Comments
Post a Comment