mockmvc.perform出错空指针异常

t30tvxxf  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(704)

我的测试控制器这是一个带有spock框架的groovy类。

class LookupControllerSpec extends Specification {

     def lookupService = Mock(LookupService)
     def lookupController = new LookupController(lookupService)

     MockMvc mockMvc = standaloneSetup(lookupController).build()

     def "should return a single lookup record when test hits the URL and parses JSON output"() {
         when:
         def response = mockMvc.perform(get('/api/lookups/{lookupId}',2L)).andReturn().response
         def content = new JsonSlurper().parseText(response.contentAsString)

         then:
         1 * lookupService.fetch(2L)

         response.status == OK.value()
         response.contentType.contains('application/json')
         response.contentType == 'application/json;charset=UTF-8'

         content.webId == 2L
     }
 }

错误:java.lang.illegalargumentexception:文本不能为null或空
我的java控制器

@RestController
@RequestMapping("/api/lookups")
@RequiredArgsConstructor
public class LookupController
{

     @NonNull
     private final LookupService lookupService;

     @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
     @ResponseBody
     public ResponseEntity<Page<LookupModel>> list(@RequestParam(required = false ) Long lookupId,  Pageable pageable)
     {
         return ResponseEntity.ok(lookupService.fetchAll(lookupId, 
 pageable));
     }
}

这对我很管用。

20jt8wwn

20jt8wwn1#

首先,您需要向spockspring添加依赖项

testImplementation('org.spockframework:spock-spring:2.0-M1-groovy-2.5')
testImplementation('org.spockframework:spock-core:2.0-M1-groovy-2.5')

testImplementation('org.springframework.boot:spring-boot-starter-test') {
   exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}

然后你可以像这样用spring做集成测试:

import org.spockframework.spring.SpringBean
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.test.web.servlet.MockMvc
import spock.lang.Specification

import javax.servlet.http.HttpServletResponse

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get

@AutoConfigureMockMvc
@WebMvcTest
class LookupControllerTest extends Specification {

    @Autowired
    private MockMvc mockMvc

    @SpringBean
    private LookupService lookupService = Mock()

    def "should return a single lookup record when test hits the URL and parses JSON output"() {
        when:
        def response = mockMvc
                .perform(get('/api/lookups/')
                        .param("lookupId", "2")
                        .param("page", "0")
                        .param("size", "0"))
                .andReturn()
                .response

        then:
        response.status == HttpServletResponse.SC_OK
    }
}

现在只需指定模拟服务。

相关问题