
1、Junit测试原理
springboot中使用junit编写单元测试默认是事物回滚的,这样测试的脏数据不影响数据库,即实际上是执行了对应的插入操作,但是完成操作后执行了事务回滚操作,从而数据库中没有对应数据。
2、关闭自动事务回滚
在对应的测试方法上添加@Rollback(false)关闭回滚。
3、记录自己的一些关于单元测试的操作步骤
-
新建单元测试类(选择要新建的测试类或者方法,快捷键Ctr+Shift+T),选择新建测试
image.png
-
我选择的是JUnit4
image.png
-
因为有一些初始之前的用户信息需要使用,所以选上Generate的setUp/@Before
image.png
-
生成出来的单元测试类差不多就这样子来
image.png
-
在测试类上加上一些注解
@Slf4j
@SpringBootTest(classes = com.bimstudy.TenantApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Transactional
@RunWith(SpringRunner.class)
public class IStudyStepServiceTest {
@Before
public void setUp() throws Exception {
}
@Test
public void saveLocal() {
}
@Test
public void getStepByLineId() {
}
}
注意:@Transactional如果要插入数据到数据库的话必须加上
- 单元测试之前需要用到的用户信息
@Autowired
IStudyLineService studyLineService;
@Before
public void setUp() throws Exception {
RequestContextListener listener = new RequestContextListener();
MockServletContext context = new MockServletContext();
MockHttpServletRequest request = new MockHttpServletRequest(context);
request.setAttribute("currentUser", User.builder()
.id(1141604025922449410L)
.userName("testTenant")
.mobile("13666666666")
.tenantId(1141600554917781506L)
.build());
listener.requestInitialized(new ServletRequestEvent(context, request));
}
- 我遇到问题的主题,单元测试跑通了,但是数据库中没数据@Rollback(false)
/**
* 学习路线-基础信息
*/
@Test
@Rollback(false)
public void saveLineLocal() {
StudyLineBaseSaveVO studyLineBaseSaveVO = StudyLineBaseSaveVO.builder()
.days(3).name("lclc路线1").remark("ddddddddddd")
.build();
studyLineService.saveLineBasicInfo(studyLineBaseSaveVO);
}
网友评论