Search code examples
jakarta-eejunitdependency-injectiondaofactory-pattern

DOA pattern without dependency injection


In our company we use DAO pattern in almost every project. This has some pros and cons but the question is not about that. We just started another project but in comparison with the others it is very simple and is not based on a DI framework. Just a simple servlet run on a cloud.

My question is: How to implement DAO pattern when DI is not available. How to mock DAOs later? They have to initialized somewhere probably inside a service class. Is it a good practice to use reflection during the tests and replace real DAOs with mocks? Another view is to use factoryDAO .. but how to use factory to return mock objects?


Solution

  • You can simply inject the DAO "by hand":

    public class MyServlet extends HttpServlet {
        private MyService service = new MyService(new MyDao());
    
        ...
    }
    

    And in your test:

    public class MyServiceTest {
    
        private MyDao mockDao;
        private MyService service;
    
        @Before
        public void prepare() {
            mockDao = mock(MyDao.class);
            service = new MyService(mockDao);
        }
    
        ...
    }