简体   繁体   English

如何从 JUnit 测试用例中的接口获取 class 实例

[英]How to i get class instance from interface in JUnit test case

In my Junit test case, i am trying to get instance of class from Factory but its always return null, APersistenceDAO and BPersistenceDAO classes implements TestDao在我的 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;
     
 }

This is my junit test code to get Dao reference这是我的 junit 测试代码获取道参考

 @MockBean
  private TestDAOFactory daoFactory;
@Test
  void populateCacheFromPersistence() {
      
      TestDao dao = daoFactory.getDao("A");//always getting null
}

Can you please kindly check what i am missing here?你能检查一下我在这里缺少什么吗?

i have added configuration as well我也添加了配置

  @Configuration
public class TestConfiguration {
    
        @Bean
        @Primary
        public TestDAOFactory daoFactory() {
            return Mockito.mock(Test.class);
        }
}

and from main test class, i have tried to get instance using并从主要测试 class 中,我尝试使用

@Autowired
  private TestDAOFactory daoFactory;

You are using a mock on the class you are testing.您正在测试的 class 上使用模拟。 It will return null if you do not configure it otherwise.如果您不进行其他配置,它将返回 null。 You need to actually instantiate the class.您需要实际实例化 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
}

i can able to fix it by adding @Profile("test") in configuration class我可以通过在配置 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM