反驳和奉承,两者都会造成不愉快的交谈——歌德
有时候我们想针对spring
的controller
进行单元测试,可以使用MockMvc
来进行
文档地址:https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html#spring-mvc-test-server
如果是springboot
,文档:https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing.spring-boot-applications

这里提到需要加上@AutoConfigureMockMvc
注解
在这个文档里提到要使用MockMvc
,先静态导入这四个类

然后按照这里的例子,依葫芦画瓢写一个,但是不一样的是,我这里返回的数据是json
,因此按照这里的文档稍加修改
最终结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| package com.ruben.simpleboot
import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.context.SpringBootTest import org.springframework.http.MediaType import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import org.springframework.test.web.servlet.result.MockMvcResultMatchers.*
@SpringBootTest @AutoConfigureMockMvc class UserControllerTest {
@Test fun testPage(@Autowired mockMvc: MockMvc) { mockMvc.perform(get("/user/page")) .andExpect(status().isOk) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.records").isArray) .andExpect(jsonPath("$.records[0].id").value(1L)) }
}
|
忘说了我这里是kotlin
,不过java
的话都一样的哈哈