mockmvc.perform出错空指针异常

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

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

  1. class LookupControllerSpec extends Specification {
  2. def lookupService = Mock(LookupService)
  3. def lookupController = new LookupController(lookupService)
  4. MockMvc mockMvc = standaloneSetup(lookupController).build()
  5. def "should return a single lookup record when test hits the URL and parses JSON output"() {
  6. when:
  7. def response = mockMvc.perform(get('/api/lookups/{lookupId}',2L)).andReturn().response
  8. def content = new JsonSlurper().parseText(response.contentAsString)
  9. then:
  10. 1 * lookupService.fetch(2L)
  11. response.status == OK.value()
  12. response.contentType.contains('application/json')
  13. response.contentType == 'application/json;charset=UTF-8'
  14. content.webId == 2L
  15. }
  16. }

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

  1. @RestController
  2. @RequestMapping("/api/lookups")
  3. @RequiredArgsConstructor
  4. public class LookupController
  5. {
  6. @NonNull
  7. private final LookupService lookupService;
  8. @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
  9. @ResponseBody
  10. public ResponseEntity<Page<LookupModel>> list(@RequestParam(required = false ) Long lookupId, Pageable pageable)
  11. {
  12. return ResponseEntity.ok(lookupService.fetchAll(lookupId,
  13. pageable));
  14. }
  15. }

这对我很管用。

20jt8wwn

20jt8wwn1#

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

  1. testImplementation('org.spockframework:spock-spring:2.0-M1-groovy-2.5')
  2. testImplementation('org.spockframework:spock-core:2.0-M1-groovy-2.5')
  3. testImplementation('org.springframework.boot:spring-boot-starter-test') {
  4. exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
  5. }

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

  1. import org.spockframework.spring.SpringBean
  2. import org.springframework.beans.factory.annotation.Autowired
  3. import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
  4. import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
  5. import org.springframework.test.web.servlet.MockMvc
  6. import spock.lang.Specification
  7. import javax.servlet.http.HttpServletResponse
  8. import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
  9. @AutoConfigureMockMvc
  10. @WebMvcTest
  11. class LookupControllerTest extends Specification {
  12. @Autowired
  13. private MockMvc mockMvc
  14. @SpringBean
  15. private LookupService lookupService = Mock()
  16. def "should return a single lookup record when test hits the URL and parses JSON output"() {
  17. when:
  18. def response = mockMvc
  19. .perform(get('/api/lookups/')
  20. .param("lookupId", "2")
  21. .param("page", "0")
  22. .param("size", "0"))
  23. .andReturn()
  24. .response
  25. then:
  26. response.status == HttpServletResponse.SC_OK
  27. }
  28. }

现在只需指定模拟服务。

展开查看全部

相关问题