Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit for both try and catch block coverage

Tags:

java

junit

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;
    }
like image 758
John Avatar asked Dec 06 '22 15:12

John


1 Answers

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());
    }
}
like image 197
esin88 Avatar answered Dec 08 '22 05:12

esin88