SpringBoot的测试框架排除指定bean

spring-boot-starter-test 编写功能测试时,排除指定的Bean

写测试类的时候,与项目中的某个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;
}
posted @     阅读(1295)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-02-04 yum安装提示无可用包
点击右上角即可分享
微信分享提示