赞
踩
今天碰到一个问题,写测试类的时候,与项目中的某个bean有冲突,必须排除。
那么我们在使用 spring boot test 写测试类的时候,怎么去排除指定的bean呢?
假如项目中有一个StudentBean
- @Component
- public class StudentBean {
- private static final AppLogger logger = AppLoggerFactory.getLogger(StudentBean.class);
-
- @PostConstruct
- public void init(){
- logger.info("加载学生信息");
- }
- }
当我们写测试类的时候,启动项目的时候会自动扫描@Component。
我们不想去使用 StudentBean的 @PostConstruct 方法,就必须排除这个Bean,模拟一个新的StudentBean。
排除项目中的StudentBean,如何做?很简单就是用
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- </dependency>
依赖下的 @MockBean注解,测试类排除原来项目中的StudentBean,模拟一个新的 StudentBean
- @RunWith(SpringRunner.class)
- @SpringBootTest(classes = TestApplication.class)
- @Slf4j
- public class BaseJunit {
-
- @MockBean
- private StudentBean bean;
-
- }
文章参考:stackoverflow 链接
类似 @MockXX 注解使用请自行搜索
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。