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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM