Archive: January 2013

Auto inject dependencies in JUnit using Mockito

Posted on by  
Sjoerd Schunselaar

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);
    }
}

Continue reading →

shadow-left