Thursday, October 30, 2008

integration tests with Wicket and Spring

I had a bear of a time getting my Wicket tests to work with services injected by Spring.

I started with the helpful Wicket-Spring unit-test instructions here; this got me through a basic test. Unfortunately, I must use Spring-managed services from my main AuthenticatedWebSession class since I'm using the standard Wicket "Auth-Roles" security (simply, without Acegi); Wicket has a helpful way to tie with Spring when it comes to the WebPage classes, but this doesn't work for the things I'm using in the main WebApplication or WebSession classes.

I found another project that uses Spring's test class AbstractTransactionalDataSourceSpringContextTests as it's parent class, and this proved to be my salvation. Basically, I extend that class and add the following 2 methods:

protected ConfigurableApplicationContext createApplicationContext(String[] locations) {
context.setServletContext(new org.springframework.mock.web.MockServletContext());
context.setConfigLocations(locations);
context.refresh();
return context;
}

protected String[] getConfigLocations() {
return new String[]{"context/backoffice-webapp.xml"};
}


Then I have to override the "onSetUpBeforeTransaction" method instead of the traditional JUnit "setUp" method:


@Override
protected void onSetUpBeforeTransaction() throws Exception {

super.onSetUpBeforeTransaction();

AuthenticatedWebApplication authenticatedWebApp = new WicketApplication() {
@Override
public void init() {
addComponentInstantiationListener(new SpringComponentInjector(this, TestHomePage.this.applicationContext));
initForAppAndTests(); // this is where I set up my global services, called by WicketApplication.init() as well
}
};
tester = new WicketTester(authenticatedWebApp);
}

That made it all work.

BTW, although I'm using Spring 2.5.5, the latest spring-mock library is only 2.0.8.

1 comment: