How to test Optional.orElseThrow() (Java)?



  • I have a method using a repository using Optional.orElseThrow inside a service.

    How to correctly implement the construction

    when(restLogRepository.findById(anyLong()).thenReturn(log);
    

    My way is obviously wrong

    Service

    public RestLogDto readById(Long id) {
        return DtoConverter.convert(
            restLogRepository.findById(id).orElseThrow(() -> new NoSuchElementException("Element not found")),
            modelMapper);
        }
    

    My Test method (wrong)

    @Test
    public void readById() {
        RestLog log = new RestLog();
        log.setLogId(LOG_ID);
    
        when(restLogRepository.findById(anyLong()).orElseThrow(any(Supplier.class))).thenReturn(log);
        RestLogDto result = DtoConverter.convert(log, mapper);
    
        assertEquals(result, logReader.readById(LOG_ID));
    }
    


  • DtoConverter entity = spy(new DtoConverter());
    entity.setId(5);
    doReturn(Optional.of(entity)).when(restLogRepository).findById(any());
    
    assertEquals(5, logReader.readById(5));
    


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2