Created
March 24, 2016 19:49
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//@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