3
@RunWith(MockitoJUnitRunner.class)
public class TestMail{    
    @Autowired(required = true)
    SomeFactory someFactory;
    private @Mock MailService mailService;
    private @Captor ArgumentCaptor<List<MailList>> mailListCaptor;
    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }  
    @PostConstruct
    public void init() throws Exception {
            logger.info("someFactory {}", someFactory);
    }
}

This is sample code. Before using mockito or the @Beofre annotation everything seems to be fine. Now its mocking the objects correctly but someFactory is not autowired correctly.

Before Mockito everything worked fine.

user1364861
  • 301
  • 1
  • 2
  • 16
  • Who/What do you think should be responsible for executing the `@PostConstruct` method or injecting the `@Autowired` field? – Sotirios Delimanolis May 21 '15 at 01:24
  • ApplicationContext.xml, Spring is responsible to autowire objects from context.xml. – user1364861 May 21 '15 at 01:25
  • How is an XML file going to do that? Do you mean Spring? Why do you think so? What Spring component is involved in running your test? – Sotirios Delimanolis May 21 '15 at 01:26
  • If I comment out mockito stuff it works fine. And mockito is working fine there is no problem with that. – user1364861 May 21 '15 at 01:27
  • ApplicationContext is part of the application. I m not doing anything special. – user1364861 May 21 '15 at 01:28
  • 1
    Just answer my question: why do you expect Spring to be involved in your test? `@Autowired` and `@PostConstruct` are **just annotations**. – Sotirios Delimanolis May 21 '15 at 01:28
  • 3
    Your test is run by `MockitoJUnitRunner`. There is no Spring involved here. – Sotirios Delimanolis May 21 '15 at 01:28
  • 1
    Look into `SpringJUnit4ClassRunner`. – Sotirios Delimanolis May 21 '15 at 01:31
  • My Suggestions: Do not use both! Use Mockito to inject the dependencies (use `@Mock` instead of `@Autowired`). Such a unit test is robust against several changes of your Spring environment (new beans or configuration will not influence the results of the test). If the test setup (stubbing) gets to complicated you should take this as an indicator that the solution is to complex (simplify it!). – CoronA May 21 '15 at 06:07

1 Answers1

0

If you want dependencies of SomeFactory to be injected to it use the @InjectMocks annotation.

http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/InjectMocks.html

Refer Mockito: Inject real objects into private @Autowired fields as well

Dev Blanked
  • 8,555
  • 3
  • 26
  • 32