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 JUnit for below code.
Here I don't want to cover any exception, but want to cover the lines of code written in the catch block using Mockito.
public Product getProductLookUpData() {
Product product = null;
try{
// Try to get value from cacheable method
product = productCacheDao.getProductLookUpData();
.....//statements
} catch (Exception ex) {
// getting value from db
product = productDao.getIpacMetricCodeLookUpData();
....//statements
}
return product;
}
You can mock both productCacheDao
and productDao
and check how many times those methods were invoked in your test cases. And you can simulate exception throwing with those mock objects, like this:
when(mockObject.method(any())).thenThrow(new IllegalStateException());
So, for your case I would do something like this:
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.*;
public class ProductTest {
private static final Product CACHED_PRODUCT = new Product("some parameters for cached product");
private static final Product DB_PRODUCT = new Product("some parameters for DB product");
private ProductService service;
private ProductDao productDaoMock;
private ProductCacheDao productCacheDaoMock;
@Before
public void setup() {
service = new ProductService();
productDaoMock = mock(ProdoctDao.class);
service.setProductDao(productDaoMock);
productCacheDaoMock = mock(ProdoctCacheDao.class);
service.setProductCacheDao(productCacheDaoMock);
}
@Test
public void testCache() {
when(productCacheDaoMock.getProductLookUpData(any())).thenReturn(CACHED_PRODUCT);
final Product product = service.getProductLookUpData();
Assert.assertEquals(CACHED_PRODUCT, product);
verify(productCacheDaoMock, times(1)).getProductLookUpData(any());
verify(productDaoMock, never()).getIpacMetricCodeLookUpData(any());
}
@Test
public void testDB() {
when(productCacheDaoMock.getProductLookUpData(any())).thenThrow(new IllegalStateException());
when(productDaoMock.getIpacMetricCodeLookUpData(any())).thenReturn(DB_PRODUCT);
final Product product = service.getProductLookUpData();
Assert.assertEquals(DB_PRODUCT, product);
verify(productCacheDaoMock, times(1)).getProductLookUpData(any());
verify(productDaoMock, times(1)).getIpacMetricCodeLookUpData(any());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With