當我嘗試在我的 Spring Boot 應用程式中測驗我的 CRUD 操作時,我得到 NullPointerException 說那this.Repository
是空的。我可以做些什么來解決這個問題?我錯過了什么嗎?
我的測驗課:
@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());
}
}
我收到 NullPointerException:
java.lang.NullPointerException: Cannot invoke "com.app.hospitalmanagementsystem.repository.AppointmentRepository.findAll()" because "this.appointmentRepository" is null
uj5u.com熱心網友回復:
由于此處標記了 spring boot,因此您使用 spring boot 2.x 的機會(這些天 1.x 已過時)
但如果是這樣,您應該運行 JUnit 5 測驗(spring boot 2.x 與 Junit 5 一起使用)
所以代替@RunWith
注釋,使用@ExtendsWith
然后在測驗中放置斷點,并確保 mockito 擴展確實有效并創建了 mock。
現在至于given
- 我不能肯定地說,我沒有使用這種語法(BDD Mockito),但在“干凈的 mockito”中應該是Mockito.when(..).thenReturn
總而言之,試試這個代碼:
@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());
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/505307.html
上一篇:需要幫助:InvocationTargetException包裹在“java.lang.ClassCastException:java.lang.Stringcannotbecastto[C”usin
下一篇:如何為我的服務層創建單元測驗?