SpringBootTest & Mockito 虚实结合测试
起因
单一使用mockito,会出现很多mock困难的问题,导致测试编写过程太长,太恶心
单一使用springboottest,会遇到需要外部接口的地方,这个时候就非得去真实调用才行。也很恶心
所以 想到了混合使用 ,这个方法非原创,纯记录,以下的内容都是自己真实的
常用注解
注解 | 使用时机 |
---|---|
@MockBean | 全部都走mock |
@SpyBean | 除特殊指定mock外,都执行真实方法 |
示例
import cn.hutool.core.util.RandomUtil;
import com.xxxx.util.exception.ServiceException;
import com.xxxx.xxx.common.core.entity.user.xxxxConfig;
import com.xxxx.xxx.common.core.utils.SecurityUtils;
import com.xxxx.xxx.common.mybatis.mapper.userMapper;
import com.xxxx.xxx.user.dto.xxxxDTO;
import com.xxxx.xxx.user.service.xxxxConfigService;
import com.xxxx.xxx.user.vo.xxxxVO;
import com.xxxx.xxx.verify.code.service.xxxxService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;@Transactional
@SpringBootTest
@Rollback
// 当模块中存在websocket的时候,需要使用下方注解配置,方可启动成功(以下配置会启动服务)
// @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class XxxxConfigServiceImplTest {@Resourceprivate XxxxConfigService xxxxConfigService;@MockBean(name = "userMapper")private UserMapper myUserMapper;@Resourceprivate XxxxService xxxxService;public static final String ACCOUNT = RandomUtil.randomString(8);public static final String TEL = RandomUtil.randomNumbers(11);@BeforeEachvoid init() {// mock方法返回Mockito.when(myUserMapper.selectTelByAccount(Mockito.anyString())).thenReturn(TEL);}@Test@DisplayName("修改:成功")void update() {// 以下都是执行真实代码xxxxDTO xxDTO = new xxxxDTO();xxDTO.setAccount(ACCOUNT);xxDTO.setPassword("123456");xxDTO.setStartTime("00:00");xxDTO.setEndTime("23:59");xxDTO.setCaptchaCode("0000");xxxxConfigService.sendCode(ACCOUNT);xxxxConfigService.update(xxDTO);xxxxConfig controlConfig = xxxxConfigService.lambdaQuery().eq(xxxxConfig::getAccount, ACCOUNT).one();assert controlConfig.getAccount().equals(xxDTO.getAccount());assert controlConfig.getStartTime().equals(xxDTO.getStartTime());assert controlConfig.getEndTime().equals(xxDTO.getEndTime());}
}
常见问题
- MockBean导致启动失败,提示 org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type ‘xxx’
解决方法:// 属性名换一个 myUserMapper@MockBean(name = "userMapper")private UserMapper myUserMapper;