- @RunWith(SpringRunner.class),底层使用JUnit,表示在测试环境跑程序。
- @SpringBootTest,表示启动整个spring工程。
service层单元测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductionCategoryRepositoryTest {
@Autowired
private ProductCategoryRepository repository;
@Test
public void saveTest() {
ProductCategory productCategory = new ProductCategory("男生最爱", 2);
ProductCategory result = repository.save(productCategory);
Assert.assertNotNull(result);
}
}
Controller层单元测试
- mockMvc.perform执行一个请求
- MockMvcRequestBuilders.get("/user/1")构造一个请求
- ResultActions.andExpect添加执行完成后的断言
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class GrilControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void girlList() throws Exception{
mvc.perform(MockMvcRequestBuilders.get("/girls"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("abc"));
}
}
常用断言Assert方法
- Assert.assertNotNull(result),结果不为空就测试通过
- Assert.assertNotEquals(0, result.size()),第一个参数为不期待出现的值,本例中result.size不为0,测试就会通过
- Assert.assertEquals(0, size),这个是期待的值
- Assert.assertTrue(“查询所有的订单列表”, orderDTOPage.getTotalElements() > 0),第一个参数是提示信息,第二个参数是判断条件
@Transactional注解使用
在单元测试中的@Transactional注解,可以保证测试方法运行完成后回滚数据,不在数据库中增加内容