单元测试的简单使用

  • @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注解,可以保证测试方法运行完成后回滚数据,不在数据库中增加内容

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值