Search code examples
javaunit-testingspring-mvcmockitopowermockito

Mockito: combine @Autowired and @Mock


I have this junit test using Mockito (an open source testing framework for Java released under the MIT License) in a The Spring Web model-view-controller (MVC) framework application

I have this test:

@RunWith(MockitoJUnitRunner.class)
public class DeviceCatalogueControllerTest {


    @InjectMocks
    private DeviceCatalogueController controller;

    @InjectMocks
    protected SessionHelper sessionHelper;

    @Mock
    private MessageSource messageSource;

    @Mock
    protected CataloqueService cataloqueService;

    @Autowired
    protected ApplicationDao applicationDao;

    @Before
    public void setUpTest() {
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
    }

    @Test
    public void testInitFormGet() throws Exception {

        System.out.println  ("SessionHelper sessionHelper --> " + sessionHelper);

        //controller.initFormGet(searchForm, localeParam, request, response, model, locale)
        controller.initFormGet(null, DEFAULT_LOCALE, request, response, null, new Locale(DEFAULT_LOCALE));
        }

but when running the test applicationDao is null


Solution

  • Your test class is totally unaware of the Spring. To use Spring in unit tests you have to use the correct annotation @RunWith(SpringJUnit4ClassRunner.class) instead of the @RunWith(MockitoJUnitRunner.class) you are using now.

    Then in the @Before method you can initialize your Mockito mocks by calling MockitoAnnotations.initMocks(this);

    Your test class can be re-coded as:

    @ContextConfiguration(locations = {"classpath:/application-context.xml"})
    @RunWith(SpringJUnit4ClassRunner.class)
    public class DeviceCatalogueControllerTest {
    
    
        @InjectMocks
        private DeviceCatalogueController controller;
    
        @InjectMocks
        protected SessionHelper sessionHelper;
    
        @Mock
        private MessageSource messageSource;
    
        @Mock
        protected CataloqueService cataloqueService;
    
        @Autowired
        protected ApplicationDao applicationDao;
    
        @Before
        public void setUpTest() {
            MockitoAnnotations.initMocks(this);
            request = new MockHttpServletRequest();
            response = new MockHttpServletResponse();
        }
    
        @Test
        public void testInitFormGet() throws Exception {
    
            System.out.println("SessionHelper sessionHelper --> " + sessionHelper);
    
            //controller.initFormGet(searchForm, localeParam, request, response, model, locale)
            controller.initFormGet(null, DEFAULT_LOCALE, request, response, null, new Locale(DEFAULT_LOCALE));
        }
    }
    

    Note: use the correct xml path for your application-context.xml in @ContextConfiguration(locations = {"classpath:/application-context.xml"})