wildf1re25
wildf1re25

Reputation: 31

"Boolean cannot be returned by findById()" Error

I am trying to write tests for an university project and I get the following error.

Boolean cannot be returned by findById()
findById() should return Optional

This is my test:

@Test
    void getStatusTest1() {
        p1.setActive(true);
        when(pollService.getStatus(1L)).thenReturn(true);
        assertTrue(pollService.getStatus(p1.getId()));

    }

And this the service method I am testing:

public boolean getStatus(long id) {
        Poll poll = pollRepository
                .findById(id).orElseThrow(() -> new IllegalStateException((
                        "Poll with id " + id + "does not exist"
                )));

        return poll.isActive();
    }

Now as you can see the method I am testing does not return an Optional but a boolean and I don't see why I get that error. findById() does indeed return Optional, but why does that affect my the return type of the method?

Upvotes: 1

Views: 426

Answers (1)

ᴇʟᴇvᴀтᴇ
ᴇʟᴇvᴀтᴇ

Reputation: 12781

Judging by the error message, the problem is due to the mocked result of the findById() method. It is not in the code you posted, but presumably is returning a boolean, rather than an Optional<Poll> which is what the signature of that method requires.

You should return an Optional.of(p1) instead:

when(pollRepository.findById(anyInt())).thenReturn(Optional.of(p1));

Upvotes: 1

Related Questions