Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffsheets/bae615833655983ea178 to your computer and use it in GitHub Desktop.
Save jeffsheets/bae615833655983ea178 to your computer and use it in GitHub Desktop.
Spring MVC unit (minimal integration) test that uses Spring config for the controller setup
package org.springframework.web.servlet.handler
import org.springframework.web.context.WebApplicationContext
/**
* Workaround to register a controller with the WebAppContext because detectHandlerMethods is protected
*
* This allows our Mvc Unit tests to use the wired up Spring Jackson converters and mappers,
* without having to specify them individually in every test
*
* Your test will need this annotation too:
* @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
*/
class AbstractHandlerMethodMappingTestOverride {
static WebApplicationContext addController(WebApplicationContext wac, Object controller) {
wac.getBean('requestMappingHandlerMapping').detectHandlerMethods(controller)
return wac
}
}
//@UnitTestDI is a helper groovy @AnnotationCollector that includes:
// @WebAppConfiguration
// @ContextConfiguration for WebMvcConfig, Validators, and Properties
// @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@UnitTestDI
class AddressControllerSpec extends Specification {
@Autowired
WebApplicationContext wac
AddressService addressService = Mock()
MockMvc mockMvc
AddressController controller = new AddressController()
def setup() {
controller.addressService = addressService
mockMvc = MockMvcBuilders.webAppContextSetup(addController(wac, controller)).build()
}
def "should test buildAddress"() {
given:
DateTime beginDate = createDateTime('10/12/2014')
AddressView view = new AddressView(number: 321)
when:
def response = mockMvc.perform(get('/api/address').param('beginDate', '10/12/2014')).andReturn()
def content = new JsonSlurper().parseText(response.contentAsString)
then:
1 * addressService.fetchAddress(beginDate) >> view
response.status == OK.value()
content.number == 321
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment