Search code examples
javaunit-testingjunitmockito

Unable to handle .isPresent() while creating Juint test cases


if (clientDetailsRepository.findIDByClientName(clientDetailRequest.getClientName()).isPresent()) {
            return CommonUtils.getResponseObject(HttpStatus.CONFLICT, req,
                    "Client with Client Name " + clientDetailRequest.getClientName() + " is already present",
                    false);
        }

while writing the Junit test case for the following :

@Test
public void setClientDetailsTest() {
    Optional<Long> opt = Optional.of(20l);
    when(clientDetailsRepository.findIDByClientName(Mockito.anyString())).thenReturn(opt);
            ResponseEntity<Object> response =  clientService.setClientDetails(req,ClientDetails());
        assertNotNull(response);
    }
    

What I have observed is that isPresent() is always returning false and it is never going inside if Statement


Solution

  • I think the issue is related to ArgumentMatcher. So try to pass the correct value, not a matcher. Example:

    @Test
    public void setClientDetailsTest() {
        String clientName = "testClient";
        ClientDetailRequest clientDetailRequest = new ClientDetailRequest();
        clientDetailRequest.setClientName(clientName);
    
        Optional<Long> opt = Optional.of(20L);
        when(clientDetailsRepository.findIDByClientName(clientDetailRequest.getClientName())).thenReturn(opt);
    
        ResponseEntity<Object> response = clientService.setClientDetails(req, clientDetailRequest);
    
        assertNotNull(response);
    }