引言
在写单元测试时,免不了遇到私有方法、数据库等一些操作,此时就需要一些mock处理。文章来源地址https://www.toymoban.com/news/detail-648614.html
代码实践
service层demo源码
public class DemoServiceImpl {
@Autowired
private DemoMapper demoMapper;
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean deleteById(Long id) {
//获取实体
DemoEntity entity = this.getDemoEntity(id);
demoMapper.deleteById(entity);
return true;
}
private DemoEntity getDemoEntity() {
//构造queryWrapper
QueryWrapper<DemoEntity> query = Wrappers.query();
//根据所属系统、是否删除筛选菜单列表
query.lambda()
//id筛选
.eq(DemoEntity::getId, id)
DemoEntity entity = demoMapper.selectOne(query);
return entity;
}
}
service层单元测试
@PowerMockRunnerDelegate(SpringRunner.class)
@RunWith(PowerMockRunner.class)
public class DemoServiceImplTest {
/**
* 注入service
*/
@InjectMocks
private DemoServiceImpl demoService;
/**
* mapper
*/
@MockBean
private DemoMapper demoMapper;
/**
* before设置
*/
@Before
public void setUp() {
//构建mybatis
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), DemoEntity.class);
}
/**
* 测试 deleteById
*/
@Test
public void deleteById() throws Exception {
//spy service
DemoServiceImpl spy = PowerMockito.spy(demoService);
//mock mapper
DemoMapper demoMapperNew = PowerMockito.mock(DemoMapper.class);
//注入到service中
Whitebox.setInternalState(spy, "demoMapper", demoMapperNew);
//构建实体
DemoEntity demoEntity = new DemoEntity();
//mock mapper结果
PowerMockito.when(demoMapperNew.selectOne(any())).thenReturn();
//mock 私有方法
PowerMockito.when(spy, "getDemoEntity", menuId).thenReturn(demoEntity);
//执行方法
Boolean result = spy.deleteById(menuId);
//断言判断
Assert.assertEquals(true, result);
}
}
文章来源:https://www.toymoban.com/news/detail-648614.html
到了这里,关于SpringBoot——Service单元测试(包含mybatis、mapper、私有方法等)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!