Wednesday, 6 July 2011

Simple Example - Use of Mockito

Mockito is very helpful for junit testing, especially for the mocking the object. No need for having setters for injecting the mock object to the bean, mockito does it in very simple way. The following example will help to understand the use of mocking of injected bean.

public class UIConfigServiceImpl implements UIConfigService {

  private UIConfigDAO uiConfigDAO;

  public List getUIConfigData(UIConfigType configType) {
    logger.debug("Inside UiConfigService");
    return uiConfigDAO.getUIConfigData(configType);

Junit Test:
@RunWith(MockitoJUnitRunner.class) // Run the Junit with Mockito Junit Runner
public class UIConfigServiceTest {

  @InjectMocks // Inject Mock objects into the service. Mockito allows to inject beans where @Autowired is used without requiring setters.
  private UIConfigService uiConfigService = new UIConfigServiceImpl();

  @Mock // Creating a mock for injected object
  private UIConfigDAO mock;

  public void testGetUIConfigData() {
    List list = new ArrayList();
    UserDetailType suc = new UserDetailType();
    List rv = uiConfigService.getUIConfigData(null);

No comments:

Post a Comment