Home > Software engineering >  How to i get class instance from interface in JUnit test case
How to i get class instance from interface in JUnit test case

Time:08-26

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

@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

 @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

@Autowired
  private TestDAOFactory daoFactory;

CodePudding user response:

You are using a mock on the class you are testing. It will return null if you do not configure it otherwise. You need to actually instantiate the 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
}

CodePudding user response:

i can able to fix it by adding @Profile("test") in configuration class

@Profile("test") 
  @Configuration
public class TestConfiguration {
    
        @Bean
        @Primary
        public TestDAOFactory daoFactory() {
            return Mockito.mock(Test.class);
        }
}
  • Related