Can @injectmocks do constructor injection And field injection?

3,287 views
Skip to first unread message

tommytastic

unread,
May 2, 2012, 4:41:41 AM5/2/12
to mockito
I have the following class,

@Service
public class ChannelIngester extends AbstractIngester<Long, Channel> {

private ChannelCategoryRepository channelCategoryRepository;

@Autowired
SystemService systemService;

@Autowired
public ChannelIngester(ChannelRepository repository,
ChannelCategoryRepository channelCategoryRepository) {
super(repository);
this.channelCategoryRepository = channelCategoryRepository;
}

And my test starts like this:

@RunWith(MockitoJUnitRunner.class)
public class ChannelIngesterTest {

@Mock ChannelCategoryRepository channelCategoryRepository;
@Mock ChannelRepository channelRepository;
@Mock SystemService systemService;
@InjectMocks ChannelIngester channelIngester;

I am using Mockito 1.9.0. The constructor injection is working fine
but the field injection is not.

The docs at http://docs.mockito.googlecode.com/hg/1.9.0/org/mockito/InjectMocks.html
say:
Mockito will try to inject mocks only either by constructor injection,
setter injection, or property injection in order and as described
below. If any of the following strategy fail, then Mockito won't
report failure; i.e. you will have to provide dependencies yourself.

It seems like once it has done constructor injection it wont attempt
to do setter or property injection. The documentation seems to agree
as it says "only either by". Is there a way to make it do all?

Maybe it would be better if it first tried constructor injection and
failing that, tried setter injection, and then checked if there were
any properties that were still null that it could inject?

Tom

Brice Dutheil

unread,
May 2, 2012, 9:03:44 AM5/2/12
to moc...@googlegroups.com
Hi,

That is correct, once the constructor injection is done the object is considered fully initialized. Constructor injection has a different meaning than property or field injection, ie, the object know itself how to initialize itself, so it was decided that Mockito will not violate the integrity of an object instantiated via a non default constructor.


To achieve what you want, you have 3 options :
 - make a package visible constructor with all you dependencies
 - use the mockito automatic injection mechanism, and in a JUnit @Before method - with a name like "inject_SystemService" - set yourself the SystemService mock
 - code the whole initialization explicitly


Does that answer your question ?

-- Brice




--
You received this message because you are subscribed to the Google Groups "mockito" group.
To post to this group, send email to moc...@googlegroups.com.
To unsubscribe from this group, send email to mockito+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mockito?hl=en.


Reply all
Reply to author
Forward
0 new messages