Issue
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?
@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
Solution
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());
}
}
Answered By - Mark Bramnik
Answer Checked By - David Marino (JavaFixing Volunteer)