当前位置:   article > 正文

spring boot test 写测试类@Test的时候,排除指定的bean_springboottest排除某些类

springboottest排除某些类

今天碰到一个问题,写测试类的时候,与项目中的某个bean有冲突,必须排除。

那么我们在使用 spring boot test  写测试类的时候,怎么去排除指定的bean呢?

假如项目中有一个StudentBean

  1. @Component
  2. public class StudentBean {
  3. private static final AppLogger logger = AppLoggerFactory.getLogger(StudentBean.class);
  4. @PostConstruct
  5. public void init(){
  6. logger.info("加载学生信息");
  7. }
  8. }

当我们写测试类的时候,启动项目的时候会自动扫描@Component

我们不想去使用 StudentBean的 @PostConstruct 方法,就必须排除这个Bean,模拟一个新的StudentBean。

 

排除项目中的StudentBean,如何做?很简单就是用 

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-test</artifactId>
  4. </dependency>

依赖下的 @MockBean注解,测试类排除原来项目中的StudentBean,模拟一个新的 StudentBean

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest(classes = TestApplication.class)
  3. @Slf4j
  4. public class BaseJunit {
  5. @MockBean
  6. private StudentBean bean;
  7. }

文章参考:stackoverflow 链接

 类似 @MockXX 注解使用请自行搜索

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号