Handling orElseThrow

2k views Asked by At

My method looks like this

public EP updateEP(long id, EP eP) {
        EE eE = eRepo.findById(id).orElseThrow(EntityNotFoundException::new);
        //some code
    }

and my test method looks like this

    @Test
    public void testUpdateEWhenEExists() {
        long id = 1l;
        EE eE = new EE();
        eE.setPosId(1l);
        eE.setPosName("pos");
        EPE ePE = new EPE();
        ePE.setEId(id);
     when(eRepo.findById(id).orElseThrow(EntityNotFoundException::new)).thenReturn(eE);
        //some code
    }

And it always throw EntityNotFoundException.I want to be returned to me eE instead of EntityNotFoundException

EDIT

    @Test
    public void testUpdateEPWhenEExists() {
        long id = 1l;
        EE eE = new E();
        eE.setPositionId(1l);
        eE.setPosName("pos");
        EPE ePE = new EPE();
        ePE.setEId(id);

        when(eRepo.findById(id)).thenReturn(Optional.of(eE));
    
    }

In this case error is

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
EPE cannot be returned by findById()
findById() should return Optional
2

There are 2 answers

3
grange On BEST ANSWER

From the code sample you've provided it seems that eRepo.findById(id) returns an Optional.

eRepo.findById(id).orElseThrow(...)

receives that Optional and basically checks, if the Optional is empty. If not, it returns the instance of EE, otherwise it throws the specified exception.

In your test there is no need to call

orElseThrow(EntityNotFoundException::new)

because you're explicitly mocking the behaviour of findById. Just do it like that:

when(eRepo.findById(id)).thenReturn(Optional.of(eE));
0
Randy On

I am posting this to help anyone find this quicker. I needed to assert the message and condition for the exception in a .orElseThrow() from an JPA repository. The normal case is obvious to return Optional.of(someDataYouAlreadyMockedUp), but to get the exception , the repository stream must get a null (Empty) so use Optional.empty() ...

In my code I have

    License license = licenseRepository.findById(licenseId).orElseThrow(() ->
        new BadRequest("License " + licenseId + " not found."));

To test and assert the value in the Test I mock it like this:

when(licenseRepository.findById(1L)).thenReturn(Optional.empty());

And then call and assert like this:

 try {
      SomeDto result = someService.getSomeStuffByLicenseId(1L);
      fail("should have already thrown exception here!");
 }catch (BadRequest br) {
      assertEquals("License 1 not found", br.getMessage());
 }