4

I have a class containing the following code:

@Inject
@Any
private Instance<SomeInterface> SomeInterfaces;

This allows me to then iterate over all implementations of that interface. Now, I want to test this, so I declare some @Mock's of those interfaces, and want to @InjectMocks them into my unit under test. But that fails.

Is it possible to do something like that nicely, or do I have to create a @Mock for Instance<SomeInterface>

Koos Gadellaa
  • 1,220
  • 7
  • 17
  • 1
    Good point, modified the title – Koos Gadellaa Aug 11 '16 at 12:45
  • The only alternative I see is to go full-CDI and setup a CDI context in your unit tests - that makes working with mock implementations all the more difficult, I really wouldn't go there in unit tests. So going down the route of a mocked `Instance`, the `@Spy` example shown [here](http://stackoverflow.com/a/20270751/424903) might be your best bet so you can force in your own implementation. – Gimby Aug 11 '16 at 13:03
  • No. Not at all. But the good news are, you just need to start CDI container, for example, with Arquillian and Mock you implementation with mockito and add to the deployment. – temaleva Aug 12 '16 at 08:12
  • @KoosGadellaa from CDI perspective, the way to mock your beans is to use `@Alternative`. That way you could use a full-blown CDI container with the same context and everything. Only the beans you choose would be replaced by your alternative implementations (e.g. mocked). If you wish me to, I can elaborate on that. – Siliarus Aug 16 '16 at 11:56

1 Answers1

2

Mockito can do the full job for unit tests. Here you want to test how you code integrates with the CDI context => you need an instance of the CDI context that you use. Of course, you could ask Mockito to inject some mocks, but that way you will test Mockito internal injection system and not your CDI context. And Mockito warns you:

Mockito is not an dependency injection framework, don't expect this shorthand utility to inject a complex graph of objects be it mocks/spies or real objects.

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • 1
    The following is more an opinion so not part of the answer: that is one of the reasons why I prefere Spring to Java EE CDI context: the former now comes with all the tools to easily build integration tests using a true Spring application context – Serge Ballesta Aug 11 '16 at 13:40
  • Good find Serge! (and yes, so far I agree, but I've been programming spring for the last 5 years and it's time to see what the other side is like ;) ) – Koos Gadellaa Aug 11 '16 at 21:48