javamockingmockitothrows

Handling orElseThrow


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

Solution

  • 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));