Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save max747/1333097 to your computer and use it in GitHub Desktop.
Save max747/1333097 to your computer and use it in GitHub Desktop.
Executing functional tests of Spring MVC Controller with AnnotationConfig
public class AnnotationConfigWebApplicationContextLoader extends AnnotationConfigContextLoader {
@Override
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
MockServletContext servletContext = new MockServletContext();
// copy of GenericWebApplicationContext#postProcessBeanFactory
beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(servletContext));
beanFactory.ignoreDependencyInterface(ServletContextAware.class);
WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, servletContext);
WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, servletContext);
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigWebApplicationContextLoader.class)
public abstract class ControllerFunctionalTestBase {
@Autowired
protected ApplicationContext context;
protected MockHttpServletRequest request;
protected MockHttpServletResponse response;
protected HandlerAdapter ha;
protected HandlerMapping mapping;
@Configuration
@EnableWebMvc
@ComponentScan(basePackageClasses = ControllerFunctionalTestBase.class, excludeFilters = { @Filter(type = FilterType.ASSIGNABLE_TYPE, value = TestConfig.class) })
static class TestConfig extends WebMvcConfigurerAdapter {
}
@Before
public void setup() {
request = new MockHttpServletRequest();
request.setCharacterEncoding("UTF-8");
response = new MockHttpServletResponse();
response.setOutputStreamAccessAllowed(true);
response.setCharacterEncoding("UTF-8");
ha = context.getBean(RequestMappingHandlerAdapter.class);
mapping = context.getBean(RequestMappingHandlerMapping.class);
}
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response) {
try {
return ha.handle(request, response, mapping.getHandler(request).getHandler());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public class JsonControllerFunctionalTest extends ControllerFunctionalTestBase {
@Test
public void test_get() throws UnsupportedEncodingException {
request.setMethod("GET");
request.setRequestURI("/user/12345/get");
handle(request, response);
assertThat(response.getContentAsString(), is("{\"result\":true}"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment