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
1 Answer 1
Since the spring boot is tagged here, the chances that you're using spring boot 2.x (1.x is outdated these days)
But if so, you should be running JUnit 5 tests (spring boot 2.x works with Junit 5)
So instead of @RunWith annotation, use @ExtendsWith
Then place the breakpoint in the test and make sure that mockito extension has actually worked and the mock is created.
Now as for the given - I can't say for sure, I haven't used this syntax (BDD Mockito), but in a "clean mockito" it should be Mockito.when(..).thenReturn
All-in-all try this code:
@ExtendsWith(MockitoExtension.class)
class AppointmentServiceTest {
@Mock
private AppointmentRepository appointmentRepository;
@InjectMocks
private AppointmentService appointmentService;
@Test
void shouldGetAllAppointments() {
List<Appointment> appointments = new ArrayList<>();
appointments.add(new Appointment());
Mockito.when(appointmentRepository.findAll()).thenReturn(appointments);
List<Appointment> expectedAppointments = appointmentService.getAllAppointments();
assertEquals(expectedAppointments, appointments);
verify(appointmentRepository.findAll());
}
}
Comments
Explore related questions
See similar questions with these tags.
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)