Hrithik Naha
Hrithik Naha

Reputation: 117

Spring Data JPA's findById cannot be invoke; nullPointerException

Im checking for the case when searched for an id which is not present in the database returns null.

But the test case keeps on interrupting with nullPointerException; It is supposed to be returning null and i guess it is doing that, but for some reason my test case is not passing it.

Test Case

@Test
    public void testFindWrongComplaintDetailsById() {
        long id = 2;

        when(emergencyComplaintRepository.findById(id)).thenReturn(null);
        assertNull(emergencyComplaintService.findComplaintDetailsById(id));
    }

Service

@Override
    public EmergencyComplaint findComplaintDetailsById(long id) {
        return emergencyComplaintDAO.findById(id);
    }

DAO

@Override
    public EmergencyComplaint findById(long id) {
        return emergencyComplaintRepository.findById(id).orElse(null);
    }

Error

Upvotes: 0

Views: 1167

Answers (2)

SSK
SSK

Reputation: 3766

You need to return the Optional.empty() for emergencyComplaintRepository.findById(id) as shown below.

@Test
    public void testFindWrongComplaintDetailsById() {
        long id = 2;

        when(emergencyComplaintRepository.findById(id)).thenReturn(Optional.empty());
        assertNull(emergencyComplaintService.findComplaintDetailsById(id));
    }

Upvotes: 1

k-wasilewski
k-wasilewski

Reputation: 4653

That's because you should return an Optional<EmergencyComplaint> from your repository's method, that's what orElse is expecting.

By the way, using this method to return null is a complete misuse. If you want to return null, the use of orElse is unnecessary, a bad practice, and it's causing you this trouble on top of everything.

Upvotes: 2

Related Questions