1、Spring Boot单元测试
创建测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductCategoryTest {
@Autowired
private ProductCategoryService productCategoryService;//创建需要测试类的对象
}
在测试类中添加测试方法
@Test
@Transactional
public void insertOne() throws IllegalAccessException {
ProductCategory productCategory = new ProductCategory();
productCategory.setCategoryId(2);
productCategory.setCategoryName("王八蛋");
productCategory.setCategoryType(2);
productCategoryService.insertProductCategory(productCategory);
}
注解说明:@Transactional
在普通方法中此注解作用为回滚事务;即当所注解的方法抛出异常时可以将数据库回滚到执行方法之前,保证了事务的一致性。
在测试类中的方法上加了此注解,可以让测试方法对数据库的所有操作在执行完之后都可以回滚到执行之前的状态。
/*
*可以添加自定义抛出特定异常时执行回滚
*/
@Transactional(rollbackFor = IllegalAccessException.class)