Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading