2

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

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

如何使用 @JsonView 模拟数据

在下面的规范中 .andExpect(content().string('{}')) 将在控制器类具有 @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);
}

构建.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'
}
4

0 回答 0