<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootApplicationTests {
@Autowired
private UserService userService;
@Test
public void testAddUser() {
User user = new User();
user.setName("john");
user.setAddress("earth");
userService.add(user);
}
}
@BeforeClass:针对所有测试,只执行一次,且必须为static void
@Before:初始化方法,执行当前测试类的每个测试方法前执行。
@Test:测试方法,在这里可以测试期望异常和超时时间
@After:释放资源,执行当前测试类的每个测试方法后执行
@AfterClass:针对所有测试,只执行一次,且必须为static void
@Ignore:忽略的测试方法(只在测试类的时候生效,单独执行该测试方法无效)
移除掉Junit4的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.3.2-RELEASE</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
@Slf4j
@ExtendWith(SpringExtension.class)
@TestMethodOrder(MethodOrderer.Alphanumeric.class)
@SpringBootTest(classes = {VipThinkICodeCourseApplication.class})
public class LearnerCourseServiceTest {
@Autowired
private LearnerCourseService learnerCourseService;
@Test
public void getLearnerCourse() {
try {
List<CouseSchedulVo> couseSchedulers = learnerCourseService.getCouseSchedulers(219772514);
System.out.println(JSONUtil.toJsonPrettyStr(couseSchedulers));
} catch (Exception e) {
log.error("单元测试出现异常!", e);
Assertions.assertTrue(true);
}
}
}
//嵌套单元测试
@SpringBootTest
@AutoConfigureMockMvc
@DisplayName("Junit5单元测试")
public class MockTest {
//....
@Nested
@DisplayName("内嵌订单测试")
class OrderTestClas {
@Test
@DisplayName("取消订单")
void cancelOrder() {
int status = -1;
System.out.println("取消订单成功,订单状态为:"+status);
}
}
}
//参数化测试
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
@DisplayName("参数化测试")
void paramTest(int a) {
assertTrue(a > 0 && a < 4);
}
//重复测试
@RepeatedTest(3)
@DisplayName("重复测试")
void repeatedTest() {
System.out.println("调用");
}
//组合测试
@Test
@DisplayName("测试组合断言")
void testAll() {
assertAll("测试item商品下单",
() -> {
//模拟用户余额扣减
assertTrue(1 < 2, "余额不足");
},
() -> {
//模拟item数据库扣减库存
assertTrue(3 < 4);
},
() -> {
//模拟交易流水落库
assertNotNull(new Object());
}
);
}
//测试超时
@Test
@Timeout(value = 3,unit = TimeUnit.SECONDS)
@DisplayName("超时测试")
void timeoutTest() {
System.out.println("超时测试");
}
@RunWith(SpringRunner.class)
@WebMvcTest(IndexController.class)
public class SpringBootTest {
@Autowired
private MockMvc mvc;
@Test
public void testExample() throws Exception {
//groupManager访问路径
//param传入参数
MvcResult result=mvc.perform(MockMvcRequestBuilders
.post("/groupManager")
.param("pageNum","1")
.param("pageSize","10"))
.andReturn();
MockHttpServletResponse response = result.getResponse();
String content = response.getContentAsString();
List<JtInfoDto> jtInfoDtoList = GsonUtils.toObjects(content,
new TypeToken<List<JtInfoDto>>() {}.getType());
for(JtInfoDto infoDto : jtInfoDtoList){
System.out.println(infoDto.getJtCode());
}
}
}
@SpringBootTest之外的注解都是用来进行切面测试的,他们会默认导入一些自动配。
@Slf4j
@SpringBootTest
@AutoConfigureMockMvc //自动配置 MockMvc
class DemoControllerTest1 {
@Autowired
private MockMvc mock;
//测试get提交
@Test
void findById() throws Exception {
MvcResult mvcResult = mock.perform(MockMvcRequestBuilders.get("/demo/find/123").characterEncoding("UTF-8"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.code").value("S0000")) //比较json结果值
.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
response.setCharacterEncoding("UTF-8");
String content = response.getContentAsString();
log.info("findById Result: {}", content);
}
//测试post提交
@Test
void save() throws Exception {
MvcResult mvcResult = mock.perform(
MockMvcRequestBuilders.post("/demo/save")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.characterEncoding("UTF-8")
.content(JSONObject.toJSONString(new DemoVo("Hello World")))
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.code").value("S0000")) //比较json结果值
.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
response.setCharacterEncoding("UTF-8");
String content = response.getContentAsString();
log.info("save Result: {}", content);
}
}
参考:https://www.cnblogs.com/myitnews/p/12330297.html
https://www.cnblogs.com/haixiang/p/13812363.html