今天碰到一个问题,写测试类的时候,与项目中的某个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 注解使用请自行搜索

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐