I need to mock LocalDateTime inside an @Async method. But mocked localdatetime does not work inside Async method.But removing async works as expected.I have attached the code so far.
public interface ConfigurationProcessor<T> {
void process(Configuration configuration);
}
Here is the implementation of above interface
@Service
public class ConfigurationProcessoeStudents10Impl implements ConfigurationProcessor<Student> {
private final StudentRepository studentRepository;
@Autowired
public ConfigurationProcessoeStudents10Impl(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
@Override
@Async
public void process(Configuration configuration) {
studentRepository.save(Student.builder().Name(configuration.name).Age(configuration.age).RegTime(LocalDateTime.now).build());
}
}
This is the unit test
@EnableAutoConfiguration
@SpringBootTest
public class StudentsC10IT {
@Autowired
ConfigurationProcessor<StudentC10> configurationProcessor;
@Test
@Tag("VerifyProcess")
@DisplayName("Verify kafka event consumer from configuration manager")
void verifyProcess(){
LocalDateTime lt = LocalDateTime.parse("2018-12-30T19:34:50.63");
try (MockedStatic<LocalDateTime> localDateTimeMockedFourMonth = Mockito
.mockStatic(LocalDateTime.class, Mockito.CALLS_REAL_METHODS)) {
localDateTimeMockedFourMonth.when(LocalDateTime::now).thenReturn(lt));
configurationProcessor.process();
}
}
}
Need to know how to mock LocalDateTime inside this @Async method without using power mockito ?
MockedStatic
is thread-local thing, as stated in Mockito docs.
Also you should call close()
for this object.
And @Async
do execution of method in different thread, and this is why your test is not working.
As possible solution for your test - disable async: see answers here