I have ContextListener which inject in ServletContext object for work with database. And this DBJoint object create in method which test:
@WebListener
public class ContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
final ServletContext servletContext =
servletContextEvent.getServletContext();
final DBJoint joint = new DBJointHandler(
"database_scripts", "authentication_database");
servletContext.setAttribute("db", joint);
}
}
For testing servletContext.setAttribute("db", joint); I need DBJoint joint for send in setAttribute.
My test:
@Test
public void whenThen() {
final ServletContextEvent event = mock(ServletContextEvent.class);
final ServletContext context = mock(ServletContext.class);
when(event.getServletContext()).thenReturn(context);
final ContextListener listener = new ContextListener();
listener.contextInitialized(event);
DBJoint joint = ..?// how to mocking this?
verify(context).setAttribute("db", joint);
}
servletContext.setAttribute("db", joint); is possibly?Thank You.
First you need to understand that your servletContext object is a mocked object and not a real object. The joint object is real and you don't need to mock.
You can possibly test servletContext.setAttribute("db", joint); using mockito verify
verify(servletContext).setAttribute(eq("db"), any(DBJoint.class));
You can mock constructor by using power mock. Try this
DBJointHandler joint = new DBJointHandler("database_scripts", "authentication_database"); try { PowerMockito.whenNew(DBJointHandler.class).withArguments("database_scripts", "authentication_database").thenReturn(joint); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With