While writing unit tests, you often have to mock dependencies like services or controllers. Often  a constructor is used to autowire the dependencies as shown in the example below. In the Test class I instantiated the ContactService using a contactRepository Mock object

@Service
public class ContactServiceImpl implements ContactService {

private final ContactRepository contactRepository;

    @Autowired
    public ContactServiceImpl(final ContactRepository contactRepository) {
    this.contactRepository = contactRepository;
    }

    public void saveContact(final Contact contact) {
    contactRepository.save(contact);
    }
}

The test class:

public class ContactServiceTest {

private final ContactRepository contactRepositoryMock = mock(ContactRepository.class);
private final ContactService contactService = new ContactService(contactRepositoryMock);

    @Test
    public void testSaveContact() {
    Contact contact = new Contact();
    contactService.saveContact(contact);

    //validate contactRepository.save is called
    verify(contactRepositoryMock).save(contact);
    }
}

In the previous example you always have to Autowire the constructor and bind the dependencies to the class variables. In the next example the code is cleaner by autowiring the mocking objects, so you don’t have to create a custom constructor or setters to set the dependencies, which makes your code more concise and easier to read.

@Service
public class ContactServiceImpl implements ContactService {

@Autowired
private final ContactRepository contactRepository;

    public void saveContact(final Contact contact) {
    contactRepository.save(contact);
    }
}

The test class:

@RunWith(MockitoJUnitRunner.class) //will initiate and inject the mocks
public class ContactServiceTest {

@Mock
private ContactRepository contactRepository; //Note the variable name must be exactly the same as used in ContactService
@InjectMocks
private final ContactService contactService = new ContactServiceImpl();

    @Test
    public void testSaveContact() {
    Contact contact = new Contact();
    contactService.saveContact(contact);

    //validate contactRepository.save is called
    verify(contactRepository).save(contact);
    }
}

Take a note of the “RunWith(MockitoJUnitRunner.class)” annotation. This annotation will initialize the annotated mock objects. An alternative is to use “MockitoAnnotations.initMocks(this)” in a setup method to initalize the annotated mock objects. More tips can be found on the Mockito RefCard: http://refcardz.dzone.com/refcardz/mockito or take a look at the mockito site: http://www.mockito.org.

shadow-left