Why @InjectMocks
might be a thing to avoid for this kind of test.
@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@Mock
private Bar bar;
@InjectMocks
private Foo foo; // created by Mockito
@Test
public void shouldCallMethod() {
// when
foo.myMethod();
// then
...
}
}
Foo.java
public class Foo {
private final Bar bar;
public Foo(Bar bar) {
this.bar = bar;
}
...
I read about this in comments to this answer: https://stackoverflow.com/a/21172873/516167
About @InjectMocks
Mark a field on which injection should be performed.
- Allows shorthand mock and spy injection.
- Minimizes repetitive mock and spy injection.
Reference: @InjectMocks JavaDoc.
Also, some people sugest that dependencies should be added by constructor, not by setters, this way the correct dependecies are guarantied at compile time. See this.
By using constructors you are forced to limit yourself in the number of components to use as a dependency reducing complexity. (This may not be easy and changes a lot the way to do things in Spring).
Update: After some time working with dependencies autowired in the constructor I have clearly noted that test are less fragile. I still need to change the tests when dependencies change but the compiler tells me where I should change it and how big the change is. Even better, now I can distinguish between changes to the test to adapt to the new code in compile time and failures added by this code in runtime.
The only disadvantage I see is that you have to comply to its rules. You may have more control if you don't use
@InjectMocks
From their docs, I added some in bold: