带有@JsonView的控制器的spock测试用例返回空内容

时间:2016-10-13 18:53:52

标签: rest testing spock json-view

我正在编写spock测试用例来测试我的Spring mvc rest webservices。

当我将@JsonView作为控制器方法的一部分时,响应内容为空。删除@Jsonview会返回数据

如何使用@JsonView

模拟数据

在下面的规范中     .andExpect(含量()的字符串(' {}')) 将在控制器类具有@JsonView

时传递

这是规范

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]
}

和控制器类

@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'
}

0 个答案:

没有答案