I am writing spock test cases for testing my Spring mvc rest webservices. I am not able to figure out how to test for the json response returned. The content in mockMvc response is always empty.
I even tried to access the model of the response but getting an exception
java.lang.AssertionError: No ModelAndView found
here is the spec
class FindAllcommunitiesSpec extends Specification{
CommunityService communityService = Mock()
CommunityResourceAssembler communityAssembler = new CommunityResourceAssembler()
ApiResourceService apiResourceService = new ApiResourceServiceImpl(communityAssembler:communityAssembler)
def communityController = new CommunityController(communityService : communityService, resourceService: apiResourceService)
def mockMvc = standaloneSetup(communityController).build()
def 'should return all Communities'(int offset, int limit) {
when:
def result = mockMvc.perform(get('/communities').param("offset", offset.toString()).param("limit", limit.toString()))
then:
1 * communityService.findAccessibleCommunities(offset, limit) >> [
new Community(id:501, title: 'community1' ),
new Community(id:502, title: 'community2' )
]
result.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().string('{}'))
//.andExpect(model().attribute("books", "dfgfdg"))
where:
offset << [10, 20]
limit << [20, 30]
}
and the controller class
@RestController
@ExposesResourceFor(Community.class)
@RequestMapping(value = "/communities", produces = MediaType.APPLICATION_JSON_VALUE)
public class CommunityController {
@JsonView(CustomView.Summary.class)
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<?> findAll(@RequestParam(value = "offset", required = false, defaultValue = APIConstants.DEFAULT_OFFSET) final int offset,
@RequestParam(value = "limit", required = false, defaultValue = APIConstants.DEFAULT_LIMIT) final int limit) {
// Get the list of communities for the given offset and limit
List<Community> communityList = communityService.findAccessibleCommunities(offset, limit);
//Add Hateoas
CommunityResources<Resource<Community>> resources = resourceService.getCommunityResources(communityList, offset, limit, totalCount);
return new ResponseEntity<CommunityResources<Resource<Community>>>(resources, HttpStatus.OK);
}
build.gradle
compile "org.codehaus.groovy:groovy-all:2.4.3"
testCompile "org.spockframework:spock-core:1.0-groovy-2.4"
compile ("org.codehaus.groovy.modules.http-builder:http-builder:0.5.2") {
exclude group: 'commons-codec', module: 'commons-codec'
}
Aucun commentaire:
Enregistrer un commentaire