如何在JUnit测试用例中从接口获取类示例

polhcujo  于 2022-11-11  发布在  其他
关注(0)|答案(2)|浏览(130)

在我的Junit测试用例中,我尝试从Factory获取类的示例,但它总是返回null,APersistenceDAO和BPersistenceDAO类实现TestDao

@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测试代码,用于获取Dao引用

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

从主测试类中,我尝试使用

@Autowired
  private TestDAOFactory daoFactory;
zqdjd7g9

zqdjd7g91#

您正在测试的类上使用模拟。如果您不进行其他配置,它将返回null。您需要实际示例化该类。

// @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
}
wlzqhblo

wlzqhblo2#

我可以通过在配置类中添加@Profile(“test”)来修复它

@Profile("test") 
  @Configuration
public class TestConfiguration {

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

相关问题