I have a Impl class like StudentServiceImpl.
@Service
@Transactional
public class StudentServiceImpl implements studentService {
public void createStudentsAccount(){
studentRepository.save(Student.builder().code("Math").startDate(OffsetDateTime.now().with(TemporalAdjusters.firstDayOfMonth()).status("ACTIVE")
.codeEndDate(OffsetDateTime.now().toLocalDate().with(TemporalAdjusters.lastDayOfMonth()))
.lastModifiedDate(OffsetDateTime.now());
}
public void expireAccounts(){
Page<Student> studentList= studentRepository.findAllByStatusNotIn(Collections
.singleton(EXPIRED), Pageable.ofSize(1));
System.out.print(studentList.get().getCodeEndDate());
if(studentList.get().getCodeEndDate().isBefore(OffsetDateTime.now().toLocalDate())){
studentRepository.save(studentList.get().setStatus(EXPIRED));
}
}
}
I need to test createStudentsAccount() with a mocked date defaultOffsetDateTimeDate1, and expireAccounts() with another mocked date defaultOffsetDateTimeDate2 which comes after defaultOffsetDateTimeDate1.
The test was written as below. createStudentsAccount() is working fine. And it saves the values according to defaultOffsetDateTimeDate1. But when I call expireAccounts() after mocking the date again, it gives java.lang.NullPointerException saying
Cannot invoke "java.time.OffsetDateTime.toLocalDate()" because the return value of "entity.Student.getCodeEndDate()" is null".
Noted that dates related attributes become null while retrieving the data from database. But other attributes of the student are retrieved fine. What should be the reason for this?
@Test()
@DisplayName("pilot")
void pilot() throws InterruptedException{
OffsetDateTime defaultOffsetDateTimeDate1 = OffsetDateTime.parse("2022-08-22T02:03:00+00:00");
OffsetDateTime defaultOffsetDateTimeDate2 = OffsetDateTime.parse("2022-09-05T10:02:00+00:00");
try( MockedStatic<OffsetDateTime> offsetDateTimeMockedTrial = Mockito.mockStatic(OffsetDateTime.class)) {
offsetDateTimeMockedTrial.when(() -> OffsetDateTime.now()).thenReturn(defaultOffsetDateTimeDate1);
studentServiceImpl.createStudentsAccount();
}
try( MockedStatic<OffsetDateTime> offsetDateTimeMockedOneMonth = Mockito.mockStatic(OffsetDateTime.class)) {
offsetDateTimeMockedOneMonth.when(() -> OffsetDateTime.now()).thenReturn(defaultOffsetDateTimeDate2);
studentServiceImpl.expireAccounts();
}
}