When I try to test my CRUD operations in my Spring Boot Applications, I get NullPointerException saying that this.Repository is null. What can I do to resolve this issue? Am I missing something?
My test class:
@RunWith(MockitoJUnitRunner.class)
class AppointmentServiceTest {
@Mock
private AppointmentRepository appointmentRepository;
@InjectMocks
private AppointmentService appointmentService;
@Test
void shouldGetAllAppointments() {
List<Appointment> appointments = new ArrayList<>();
appointments.add(new Appointment());
given(appointmentRepository.findAll()).willReturn(appointments);
List<Appointment> expectedAppointments = appointmentService.getAllAppointments();
assertEquals(expectedAppointments, appointments);
verify(appointmentRepository.findAll());
}
}
I am getting NullPointerException:
java.lang.NullPointerException: Cannot invoke "com.app.hospitalmanagementsystem.repository.AppointmentRepository.findAll()" because "this.appointmentRepository" is null
givenandverifymethods? To which library do they belong? Probably makes sense to add a corresponding taggivenis fromorg.mockito.BDDMockitoandverifyis fromorg.mockito.Mockito. Maybe the issue is caused by wrong static imports?Mockito.when(appointmentRepository.findAll()).thenReturn(appointments);Also, Are you sure you're running with JUnit 4 I mean is it your real intention? Or you need JUnit 5 really?@RunWith()with@DataJpaTestand it works fine. Thank you.@DataJpaTestis a compeletely different beast :) Its not even a unit test anymore, it runs Spring infrastructure with real repositories, so make sure you understand the difference. For plain Unit test powered by JUnit 5, use@ExtendsWIth(MockitoExtension.class)