问题
I am trying to learn Batch and Tasklet.
I am writing a test case for a Tasklet code in spring batch. I am setting a map in my Test class and debug, the actual class is not having the key which I am passing from my test class.
MyEventTasklet.java
public class MyEventTasklet implements Tasklet {
public RepeatStatus execute (StepContribution contribution, ChunkContext chunkContext){
TreeMap<String, Map<Integer, Set<Student>>> studentMap = chunkContext.getStepContext().getJobExecutionContext().get("keyOfStudentMap");
}
}
MyEventTaskletTest.java
@RunWith(MockitoJunitRunner.class)
public class MyEventTaskletTest{
@Mock
StepContribution stepContribution;
@Mock
ChunkContext chunkContext;
@Mock
StepContext stepContext;
@InjectMocks
MyEventTasklet myEventTasklet = new MyEventTasklet();
@Test
public void testExecute(){
TreeMap<String, Map<Integer, Set<Student>>> studentMap = new TreeMap<>();
Map<Integer, Set<Student>> m2 = new TreeMap<>();
m2.put(100, createStudentData());
studentMap.put("keyOfStudentMap", m2);
Map<String, Object> map = new TreeMap<>();
map.put("keyOfStudentMap", new Object());
chunkContext = Mockito.mock(ChunkContext.class);
stepContribution = Mockito.mock(StepContribution.class);
stepContext = Mockito.mock(StepContext.class);
Mockito.when(stepContext.getJobExecutionContext()).thenReturn(map);
Mockito.when(chunkContext.getStepContext()).thenReturn(stepContext);
Mockito.when(chunkContext.getStepContext().getJobExecutionContext().get("keyOfStudentMap"))
.thenReturn((TreeMap<String, Map<Integer, Set<Student>>>)studentMap);
// When I am debugging I can see here, the studentMap object which is having something like {keyOfStudentMap={100=[StudentObject]}},
but when I see in actual class it is becoming {100=[StudentObject]}
}
}
I am not sure why this is happening, I am doing something wrong? Any kind of help would be highly appreciated.
回答1:
Your problem is here:
Mockito.when(stepContext.getJobExecutionContext()).thenReturn(map);
map
is not an ExecutionContext
. You should be mocking/stubbing an ExecutionContext
instance and not a Map<String, Object>
instance. Your tasklet should be calling:
chunkContext.getStepContext().getStepExecution().getJobExecution().getExecutionContext()
instead of:
chunkContext.getStepContext().getJobExecutionContext()
来源:https://stackoverflow.com/questions/61600546/spring-batchtest-case-for-tasklet-key-is-not-appearing-in-actual-class-when-i