Details
-
Type:
New Feature
-
Status:
Open
-
Priority:
Major
-
Resolution: Unresolved
-
Affects Version/s: Release 1.5
-
Fix Version/s: Release 1.6
-
Component/s: Context Management
-
Labels:None
Description
I have modified my copy of the Trunk to allow for adding and removing ServletContextListeners to be Mock tested. I have included my code for your consideration. To allow for easier testing I pass in new()d class instances. This also avoids possible typing errors by passing in Strings as in a standard web.xml file This also allows for simpler testing (see my example test class below).
From MockServletContext.java
private List<ServletContextListener> listeners = new ArrayList<ServletContextListener>();
public void removeListeners() {
ServletContextEvent e = new ServletContextEvent(this);
if (listeners == null || listeners.size() == 0) { return; }
for (ServletContextListener l : listeners) {
l.contextDestroyed(e);
}
listeners.clear();
}
public void addListener(ServletContextListener listener) { ServletContextEvent e = new ServletContextEvent(this); listener.contextInitialized(e); listeners.add(listener); }
public void addListeners(List<ServletContextListener> l) {
for (ServletContextListener s : l) {
addListener(s);
}
}
From my test class:
public class ListenerT {
private MockServletContext context = MockTestFixture.getServletContext();
@Test
public void addListeners() {
List<ServletContextListener> listeners = new ArrayList<ServletContextListener>();
listeners.add(new ServletContextListener() {
public void contextDestroyed(ServletContextEvent event) {
event.getServletContext().removeAttribute("ListenerOne");
}
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute("ListenerOne", "ListenerOneMessage");
}
});
listeners.add(new ServletContextListener() {
public void contextDestroyed(ServletContextEvent event) { event.getServletContext().removeAttribute("ListenerOne"); } }
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute("ListenerTwo", "ListenerTwoMessage");
}
});
context.addListeners(listeners);
assertEquals("ListenerOneMessage", (String) context.getAttribute("ListenerOne"));
assertEquals("ListenerTwoMessage", (String) context.getAttribute("ListenerTwo"));
}
@Test(dependsOnMethods = "addListeners")
public void removeListeners() {
context.removeListeners();
}
}
Attached diff / patch file so this maybe makes it into the next release. This patch does not contain the "mass adder" for listeners because it wouldn't fit in the existing class design. On the other hand, it includes a "removeFilters()" method (which I currently implement directly in the test fixture).
I really like improvements regarding unit tests