mardi 20 octobre 2020

mockito throwing null pointer exception on Mocked Object

Am new to mockito. I did lot of debugging yet am unable to find the solution. My test is throwing null pointer exception for one of the mock object method call where as it is passing for another mocked object. Below is my code

public class POServiceImpl implements POService {
    private final PODao poDao;
        
    @Inject
    public POServiceImpl(PODao poDao){
        this.poDao = poDao;
    }
    @Autowired
    CCPOService ccPOService ;
  
    @Override
    public Set<String> getPO(UUID a, UUID b) {
        Set<String> po= poDao.getPO(a, b);
        Set<String> ccpo= ccPOService.getPO(a, b);
        return Stream.concat(ccpo.stream(), po.stream()).collect(Collectors.toSet());
    }
    
}

public class CCPOServiceImpl implements CCPOService {
    private final CCPODao ccpoDao;
        
    @Inject
    public POServiceImpl(CCPODao ccpoDao){
        this.ccpoDao = ccpoDao;
    }
    @Override
    public Set<String> getPO(UUID a, UUID b) {
        return ccpoDao.getPO(a, b);
    }
}

My Test class is as follows

@Test
public class POServiceImplTest {
    @Mock
    PODao poDao;

    @Mock
    CCPOService ccpoService;
    
    @BeforeMethod(alwaysRun = true)
    public void beforeMethod() {
        MockitoAnnotations.initMocks(this);
    }
    
    @Test
    public void testPO() {
      final POService porderService = new POServiceImpl(poDao);
      Set<String> res = new HashSet<String>();
      res.add("PO");
      Set<String> res1 = new HashSet<String>();
      res1.add("CCPO");
      when(poDao.getPO(UUID.fromString("6af27ba7-b668-4571-b673-4a79fc203429"), UUID.fromString("6af27ba7-b668-4571-b673-4a79fc203429"))).thenReturn(res);
      when(ccpoService.getpo(UUID.fromString("6af27ba7-b668-4571-b673-4a79fc203429"), UUID.fromString("6af27ba7-b668-4571-b673-4a79fc203429"))).thenReturn(res1);
      Set<String> result = porderService.getPO(UUID.fromString("6af27ba7-b668-4571-b673-4a79fc203429"), UUID.fromString("6af27ba7-b668-4571-b673-4a79fc203429"));
      Assert.assertEquals(res.contains("PO"), result.contains("PO"));
      Assert.assertEquals(res.contains("CCPO"), result.contains("CCPO"));
    }
}

Test case is giving right mocked Set object for Set<String> po= poDao.getPO(a, b); , but it is throwing null pointer exception for line Set<String> ccpo= ccPOService.getPO(a, b); I believe @autowired ccPOService object is null. Any help appreciated

Aucun commentaire:

Enregistrer un commentaire