JUnit for both try and catch block coverage

前端 未结 3 1796
陌清茗
陌清茗 2021-02-06 17:37

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

3条回答
  •  感情败类
    2021-02-06 18:14

    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));
        }
    }
    

提交回复
热议问题