首页 > 解决方案 > 使用 Kotlin 和 JUnit 5 测试 rest api

问题描述

我正在从我的 Rest API 做睾丸,但我无法测试控制器的“插入”。

我的控制器

@PostMapping(value = ["/api/clients/lp"])
    override fun insert(@Valid @RequestBody model: LegalPersonModel): ResponseEntity<Any> {
        service.insert(service.modelToEntity(model))
        return ResponseEntity.ok().body(HttpStatus.CREATED)
    }

我的测试

val lp = LegalPerson(1L, 1L, true, "Test Fantasy", "Test LTDA",
            "test@com", "40.492.967/0001-52", "Test S", "Test M",
            LocalDate.of(2017, 10, 21), 1L, listOf(1L, 22L))
@Test
    fun insert() {
        Mockito.doReturn(lp).`when`(service)!!.insert(lp)
        mockMvc?.perform(MockMvcRequestBuilders.post("/api/clients/lp")
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .contentType(ObjectMapper().registerModule(JavaTimeModule()).let {
                    it.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
                    it.writeValueAsString(lp)
                }))
                ?.andExpect(MockMvcResultMatchers.status().isCreated)
                ?.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
    }

错误:

org.springframework.http.InvalidMediaTypeException: Invalid mime type "{"id":1,"companyId":1,"active":true,"tradeName":"Test Fantasy","companyName":"Test LTDA","email":"test@com","cnpj":"40.492.967/0001-52","stateRegistration":"Test S","municipalRegistration":"Test M","openingDate":"2017-10-21","address":1,"phones":[1,22]}": Invalid token character '{' in token "{"id":1,"companyId":1,"active":true,"tradeName":"Test Fantasy","companyName":"Test LTDA","email":"test@com","cnpj":"40.492.967"

标签: restapikotlinjunit5

解决方案


我认为您的意思是写content而不是contentTypeObjectMapper.


推荐阅读