欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 明星 > SpringBootTest Mockito 虚实结合编写测试

SpringBootTest Mockito 虚实结合编写测试

2024/10/24 23:25:36 来源:https://blog.csdn.net/qq_43652321/article/details/142669785  浏览:    关键词:SpringBootTest Mockito 虚实结合编写测试

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;
    

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com