jeudi 10 juin 2021

Mocking an if condition within a for loop in JUnit

I am trying to mock a method using Mockito and JUnit. For some reason it keeps saying that the embedded method is never being invoked, despite the test fulfilling the if statement.

Here is my method that I am testing:

    public List<LifeProduct> prune(List<LifeProduct> products) {
        for (LifeProduct product : products) {
            int id = product.getProductAnalyticsIdentifier();
            boolean deleteAnnuity = id > 10014;
            boolean deleteLifeInsurance = product.getLifeInsurance()
                .getHighLevelLifeInsuranceGroupName()
                .equals("string");
            
            if (deleteAnnuity) {
                annuityService.deleteAnnuityById(id);
            }
            if (deleteLifeInsurance) {
                lifeInsuranceService.deleteLifeInsuranceById(id);
            }
        }
        
        return products;
    }

and here is my test with the iterator setup:

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
  
        when(mockList.iterator()).thenReturn(mockIterator);
        when(mockIterator.hasNext()).thenReturn(true, false);
        when(mockIterator.next()).thenReturn(mockProduct);
    }

    @Test
    public final void testPrune() throws Exception {
        for (LifeProduct mockProduct : mockList) {
            mockProduct.setProductAnalyticsIdentifier(99999999);
            doNothing().when(annuityService).deleteAnnuityById(anyInt());
            List<LifeProduct> response = lifeProductDelegate.prune(mockList);
            assertNotNull(response);
            verify(annuityService).deleteAnnuityById(anyInt());
        }
    }

Aucun commentaire:

Enregistrer un commentaire