I am trying to write a JUnit for below code but I am not getting any idea how to cover the code which is written in catch block statement. Please can any one write a sample JUni
Mockito, or another mocking framework can be used. You will need two test cases - with and without the exception being thrown. You can mock your DAOs to return a known object so you verify your service is exhibiting the correct behaviour.
I've written a full example below.
public class MocksExample {
private ProductService service;
@Mock
private ProductDao productDao;
@Mock
private ProductCacheDao productCacheDao;
@Mock
private Product product;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
service = new ProductService();
service.setProductCacheDao(productCacheDao);
service.setProductDao(productDao);
}
@Test
public void serviceReturnsProduct() {
when(productCacheDao.getProductLookUpData()).thenReturn(product);
assertThat(service.getProductLookUpData(), is(product));
}
@Test
public void ipacProductReturnedWhenDaoThrowsException() {
when(productDao.getIpacMetricCodeLookUpData()).thenReturn(product);
when(productCacheDao.getProductLookUpData()).thenThrow(new IllegalStateException("foo"));
assertThat(service.getProductLookUpData(), is(product));
}
}