私人定制app,网站优化资源,al万词推广网站引流,做微商网站公司SpringBootTest Mockito 虚实结合测试
起因
单一使用mockito#xff0c;会出现很多mock困难的问题#xff0c;导致测试编写过程太长#xff0c;太恶心 单一使用springboottest#xff0c;会遇到需要外部接口的地方#xff0c;这个时候就非得去真实调用才行。也很恶…SpringBootTest Mockito 虚实结合测试
起因
单一使用mockito会出现很多mock困难的问题导致测试编写过程太长太恶心 单一使用springboottest会遇到需要外部接口的地方这个时候就非得去真实调用才行。也很恶心 所以 想到了混合使用 这个方法非原创纯记录以下的内容都是自己真实的
常用注解
注解使用时机MockBean全部都走mockSpyBean除特殊指定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);}TestDisplayName(修改成功)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’ 解决方法 // 属性名换一个 myUserMapperMockBean(name userMapper)private UserMapper myUserMapper;