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