![](/img/trans.png)
[英]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.