Just had a hard time to create a Junit Test with Wicket, Spring and Mockito. Finally I succeeded and want to share the solution.
The usecase is simple: a test if rendering of the homepage succeeds. The tricky part was the instantiation of the real Wicket Webapplication ( not a MockWebapplication ) with the Spring Context. Without any special arrangements instantiation of the Webapplication led to the following stacktrace:
java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered? at org.springframework.web.context.support.WebApplicationContextUtils. getRequiredWebApplicationContext(WebApplicationContextUtils.java:90)
To bypass this I override the method getServletContext in the WicketApplication and give Spring what it needs. This way i can test Wicket pages with Spring and using mocks with Mockito.
@RunWith(MockitoJUnitRunner.class) public class TestHomePage { private WicketTester tester; private YourWicketApplication app; @Mock private Service aService; @Before public void setUp() throws IOException, Exception { MockitoAnnotations.initMocks(this); tester = new WicketTester(app = new YourWicketApplication(){ /** * adjust the servletcontext to contain a WebApplicationContext */ @Override public ServletContext getServletContext() { ServletContext servletContext = super.getServletContext(); XmlWebApplicationContext applicationContext = new XmlWebApplicationContext(); applicationContext.setConfigLocation("classpath:applicationContext.xml"); applicationContext.setServletContext(servletContext); applicationContext.refresh(); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext); return servletContext; } }); // replace spring bean with a mock app.setService(aService); Serializer serializer = new Persister(); ListOfStuff list = serializer.read(ListOfStuff.class, new ClassPathResource("listofstuff.xml"). getInputStream()); when(aService.getList()).thenReturn(list); } @Test public void homepageRendersSuccessfully() { //start and render the test page tester.startPage(HomePage.class); //assert rendered page class tester.assertRenderedPage(HomePage.class); verify(aService).getList(); } }