SpringBoot——Service单元测试(包含mybatis、mapper、私有方法等)

引言

  在写单元测试时,免不了遇到私有方法、数据库等一些操作,此时就需要一些mock处理。

代码实践

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);
    }
}

你可能感兴趣的:(开发模板总结,Spring,&,SpringBoot等框架技术,#,Spring,Boot框架,mybatis,spring,boot,单元测试)