[英]How do I get the test class instance JUnit is running test cases on from inside the ClassRunner?
[英]How to i get class instance from interface in JUnit test case
在我的 Junit 測試用例中,我試圖從工廠獲取 class 的實例,但它總是返回 null、APersistenceDAO 和 BPersistenceDAO 類實現
@Component
public class TestDAOFactory {
public TestDao(String type) {
TestDaodao= null;
System.out.println("dao type "+type);
switch(type) {
case "A":
dao = new APersistenceDAO();
break;
case "B":
dao= new BPersistenceDAO();
break;
}
return dao;
}
這是我的 junit 測試代碼獲取道參考
@MockBean
private TestDAOFactory daoFactory;
@Test
void populateCacheFromPersistence() {
TestDao dao = daoFactory.getDao("A");//always getting null
}
你能檢查一下我在這里缺少什么嗎?
我也添加了配置
@Configuration
public class TestConfiguration {
@Bean
@Primary
public TestDAOFactory daoFactory() {
return Mockito.mock(Test.class);
}
}
並從主要測試 class 中,我嘗試使用
@Autowired
private TestDAOFactory daoFactory;
您正在測試的 class 上使用模擬。 如果您不進行其他配置,它將返回 null。 您需要實際實例化 class。
// @MockBean <-- Remove this
private TestDAOFactory daoFactory = new TestDAOFactory(); // Or add it in a setup method
@Test
void populateCacheFromPersistence() {
TestDao dao = daoFactory.getDao("A");//always getting null
}
我可以通過在配置 class 中添加 @Profile("test") 來修復它
@Profile("test")
@Configuration
public class TestConfiguration {
@Bean
@Primary
public TestDAOFactory daoFactory() {
return Mockito.mock(Test.class);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.