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.

Service:
public class UIConfigServiceImpl implements UIConfigService {

  @Autowired
  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;

  @Test
  public void testGetUIConfigData() {
    List list = new ArrayList();
    UserDetailType suc = new UserDetailType();
    list.add(suc);
    Mockito.when(mock.getUIConfigData(null)).thenReturn(list);
    List rv = uiConfigService.getUIConfigData(null);
    Assert.assertNotNull(rv);
    Assert.assertFalse(rv.isEmpty());
  }
}

No comments:

Post a Comment