java - 回调 Junit 不适用于 ExecutorService
问题描述
我有下面的课程很好。我在下面写了Junit objectMapper.writeValueAsString(producerRecord.value()
。我的 Junit 开始正常工作
- 如果我删除执行程序服务提交,我的 Junit 开始正常工作。
- 或者,如果
ObjectMapper m = new ObjectMapper();m.writeValueAsString(e);
我奇怪地添加了我的 Junit,即使使用 ExecutorService ,我的测试也开始正常工作。我不明白为什么该解决方案有效。
我怎样才能使 Junitwork 与 ExecutorService 提交和没有第二点“黑客:
private final ExecutorService executorService = Executors.newSingleThreadExecutor();
public void sendMessage(List<Employee> empList) {
ObjectMapper objectMapper = new ObjectMapper();
for (Employee emp : empList) {
ListenableFuture<SendResult<String, Employee>> listenableFuture = kafkaTemplate.send(topic,emp );
listenableFuture.addCallback(new ListenableFutureCallback<SendResult<String, Employee>>() {
@Override
public void onSuccess(SendResult<String, Employee> result) {
executorService.submit(() -> saveResultInDatabase(result.getProducerRecord());
}
//onFailure ommiteed for brevity
private void saveResultInDatabase(ProducerRecord<String, Employee> producerRecord)
EmpObj e= new EmpObj();
e.setSalary(producerRecord.value().getSalary());
try {
System.out.println(" in here 1"); // JUNIT reaches here and stops
// objectMapper.writeValueAsString(producerRecord.value() is not run and doesn't throw any error
e.setMsg(objectMapper.writeValueAsString(producerRecord.value()));
System.out.println(" in here 2"); // JUNIT never reaches here
} catch (Exception e) {
// JUNIT never reaches here
System.out.println(" in here 3");
}
// JUNIT never reaches here
System.out.println(" in here 4");
我的Junit在这里
Employee e = new Employee();
List<Employee> employeeList = new ArrayList<>();
employeeList .add(e);
ListenableFuture<SendResult<String, Employee>> responseFuture = mock(ListenableFuture.class);
SendResult<String, Employee> sendResult = mock(SendResult.class);
ProducerRecord<String, Employee> producerRecord = mock(ProducerRecord.class);
when(kafkaTemplate.send(null,e)).thenReturn(responseFuture);
when(sendResult.getProducerRecord()).thenReturn(producerRecord);
when(producerRecord.value()).thenReturn(e);
doAnswer(invocationOnMock -> {
ListenableFutureCallback<SendResult<String, Employee>> listenableFutureCallback = invocationOnMock.getArgument(0);
listenableFutureCallback.onSuccess(sendResult);
return null;
}).when(responseFuture).addCallback(any(ListenableFutureCallback.class));
myKafkaService.sendMessage(employeeList); //invocation to my real method
解决方案
推荐阅读
- php - 如何将一组自定义分类术语应用于可搜索的下拉列表?
- javascript - 为什么在 MVC Web 应用程序中会出现此 Javascript 错误?
- java - 如何从 DynamoDB 数据中以字符串形式获取价格
- bpmn - 有没有办法将 jar 连接到 flowable admin
- cocoa - 排除使用 NSTextView/UITextView 无法正确移动文本
- unix - 通过终端命令触发 Visual Studio 代码启动程序“开始调试”
- javascript - 使用 .reduce 时出现 UnhandledPromiseRejectionWarning
- math - 一般单调函数方程
- elisp - 不区分大小写的文本列表排序
- python - 使用 numpy 的任务