Spring Batch: How to cast stepContext.getJobExecutionContext() into custom Map implementation in mockito when then

huangapple 未分类评论49阅读模式
英文:

Spring Batch: How to cast stepContext.getJobExecutionContext() into custom Map implementation in mockito when then

问题

这个问题与这个问题相关。我为什么在这里提问,而不是更新那个问题呢?因为这可能是一个有帮助的问题,与我之前提出的问题无关。

在一个测试类中,我如何对下面的实现进行类型转换:
假设我有一个类似这样的映射:TreeMap<String, Map<Integer, Set<Student>>>

我想要将默认的chunkContext.getStepContext().getJobExecutionContext()(类型为Map<String, Object>)在我的测试类中转换为TreeMap<String, Map<Integer, Set<Student>>>

现有的实现是:

Mockito.when(chunkContext.getStepContext().getJobExecutionContext().get("keyOfStudentMap"))
        .thenReturn((TreeMap<String, Map<Integer, Set<Student>>>)studentMap);

当我悬停在getJobExecutionContext()上时,它显示为Map<String, Object>,我想以一种方式进行更改,使其变为TreeMap<String, Map<Integer, Set<Student>>>

如果有任何不清楚的地方,对不起。我可以根据您的评论更新问题。:)

英文:

This question is related to This. Why I am asking here and not updating the question, because this can be helpful question and not related to the previous one which I have asked.

In a Test class how I can cast the below implementation:
Lets say I have a map like this: TreeMap<String, Map<Integer, Set<Student>>>

and I want to cast the default chunkContext.getStepContext().getJobExecutionContext() which is Map<String, Object> to TreeMap<String, Map<Integer, Set<Student>>> in my Test class.

Existing implementation is:

Mockito.when(chunkContext.getStepContext().getJobExecutionContext().get("keyOfStudentMap"))
            .thenReturn((TreeMap<String, Map<Integer, Set<Student>>>)studentMap);

when I hover in getJobExecutionContext(), it shows Map<String, Object> and want to change in a way where this can changed to TreeMap<String, Map<Integer, Set<Student>>>

Sorry if anything is unclear. I can update the question based on your comments. Spring Batch: How to cast stepContext.getJobExecutionContext() into custom Map implementation in mockito when then

答案1

得分: 0

代替原来的写法:

chunkContext.getStepContext().getJobExecutionContext()

你需要使用:

chunkContext.getStepContext().getStepExecution().getJobExecution().getExecutionContext()

这将返回一个 ExecutionContext 的实例。

现在,无论你在 ExecutionContext 中放入什么作为键,在调用 get 时都会按原样返回,因此你可以将其强制转换为原始类型(在你的情况下为 TreeMap<String, Map<Integer, Set<Student>>>)。

英文:

Instead of doing:

chunkContext.getStepContext().getJobExecutionContext()

you need to use:

chunkContext.getStepContext().getStepExecution().getJobExecution().getExecutionContext()

which returns an instance of ExecutionContext.

Now whatever you put as key in ExecutionContext, you get is as is when calling get and hence you can cast it to the original type (TreeMap&lt;String, Map&lt;Integer, Set&lt;Student&gt;&gt;&gt; in your case).

huangapple
  • 本文由 发表于 2020年5月5日 05:10:44
  • 转载请务必保留本文链接:https://java.coder-hub.com/61601670.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定