引入依赖
<!-- springboot 的 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- springsecurity 的 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
单元测试编写
@TestInstance(Lifecycle.PER_CLASS)
@SpringBootTest
@AutoConfigureMockMvc
@ContextConfiguration(classes = { YourApplication.class, SecurityCfg.class })
@WithUserDetails("admin") /// 模拟登录用户,这里模拟admin
@TestMethodOrder(MethodOrderer.OrderAnnotation.class) /// 测试顺序类型
public class AbcControllerTest {
private String root = "/abc";
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
//// 配置spring security 测试
@Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).apply(SecurityMockMvcConfigurers.springSecurity())
.build();
}
@Order(1) /// 顺序
@Test
void addTest() throws Exception {
/// post
MockHttpServletRequestBuilder request = MockMvcRequestBuilders
.post(this.root + "/addJxXl").param("xnq", "2022-2023-1").param("ksrq", "2022-09-01").param("jsrq", "2023-03-01");
mockMvc.perform(request).andExpect(MockMvcResultMatchers.status().isOk());// .andExpect(MockMvcResultMatchers.content().string("成功"));
}
/// application/json 传值方式
@Order(1)
@Test
void setUGroupTest(@Autowired MockMvc mvc) throws Exception {
List<Integer> appids = new ArrayList<Integer>();
List<String> ugpids = new ArrayList<String>();
MockHttpServletRequestBuilder request = MockMvcRequestBuilders.post(this.root + "/setUGroup");
Map<String, Object> params = new HashMap<String, Object>();
params.put("appids", appids);
params.put("ugpids", ugpids);
appids.add(10013);
ugpids.add("faac9cf6");
ugpids.add("e4b9ca7221530f");
ugpids.add("5925d336a-6e93ee46f476");
request.contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(params));
// mockMvc.perform(request).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$.code",
// Matchers.e(200)));
}
}
网友评论