Shorthand Notation for Mock Creation
Contents
Mockito provides a shorthand notation, which is really expressive, to inject the mock dependencies.
Note that this technique: • Only works for class scope, not for method scope. • We must run the test class with MockitoJUnitRunner.class.
// ...
@RunWith(MockitoJUnitRunner.class)
public class AuthenticatorApplicationTest {
@Mock
private AuthenticatorInterface authenticatorMock;
@InjectMocks
private AuthenticatorApplication authenticator;
// ...
}With the @Mock annotation, we define the dependencies to inject. And then, with @InjectMocks, we specify where to inject the defined dependencies. With only those annotations, we have an instance of AuthenticatorApplication with the AuthenticatorInterface injected.
To perform the injection, Mockito tries the following ways, in order: • By constructor. • By setter. • By class field.
If Mockito is unable to do the injection, the result will be a null reference to the object to be injected, which in this case, would be AuthenticatorApplication.
But, as we have a constructor where the interface is passed, Mockito is supposed to do the injection properly. So now, we could make another test case to test it: AuthenticatorApplicationTest.java
@Test
public void testAuthenticateMockInjection() throws EmptyCredentialsException {
String username = "javacodegeeks";
String password = "s4f3 p4ssw0rd";
when(this.authenticatorMock.authenticateUser(username, password))
.thenReturn(true);
boolean actual = this.authenticator.authenticate("javacodegeeks",
"s4f3 p4ssw0rd");
assertTrue(actual);
}We don’t have to do anything more than the test itself, Mockito has created an instance for the AuthenticatorApplication with the injected mock.