Just figured out how to do UnitTesting with Spring 3 and Wicket.
Spring 3 introduced a check to see if a given context was a
WebApplicationContext. That means ApplicationContextMock is not suitable for
testing (giving the infamous " No WebApplicationContext found: no
ContextLoaderListener registered?" message).
I simply extended the class and added WebApplicationContext interface.

The following example shows how to get it going (I hope the code doesn't get
messed up):


public class TestHomePage extends TestCase {

private WicketTester tester;


 @Override

public void setUp() {

final WebApplicationContextMock appctx = new WebApplicationContextMock();


 final ServiceOfDoom mock = createMock(ServiceOfDoom.class);

expect(mock.getIt()).andReturn("whups").anyTimes();

replay(mock);

 tester = new WicketTester(new WicketApplication()) {

@Override

public ServletContext newServletContext(String path) {

MockServletContext servletContext = (MockServletContext) super

.newServletContext(path);

appctx.setServletContext(servletContext);

appctx.putBean("scratchy", mock);

servletContext

.setAttribute(

WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,

appctx);

return servletContext;

}

};

tester.getApplication().addComponentInstantiationListener(

new SpringComponentInjector(tester.getApplication(), appctx,

false));

}


 public void testRenderMyPage() {

// start and render the test page

tester.startPage(HomePage.class);


 // assert rendered page class

tester.assertRenderedPage(HomePage.class);


 // assert rendered label component

tester

.assertLabel("message",

"whups");

}


 private class WebApplicationContextMock extends ApplicationContextMock

implements WebApplicationContext {

private ServletContext servletContext;


 public <T> T getBean(Class<T> requiredType) throws BeansException {

// TODO Auto-generated method stub

return null;

}


 public <A extends Annotation> A findAnnotationOnBean(String beanName,

Class<A> annotationType) {

// TODO Auto-generated method stub

return null;

}


 public Map<String, Object> getBeansWithAnnotation(

Class<? extends Annotation> annotationType)

throws BeansException {

// TODO Auto-generated method stub

return null;

}


 public void setServletContext(ServletContext servletContext) {

this.servletContext = servletContext;

}


 public ServletContext getServletContext() {

return null;

}


 }

}

Reply via email to