0

我正在尝试学习 Batch 和 Tasklet。

我正在为 Spring Batch 中的 Tasklet 代码编写测试用例。我在我的测试类中设置一个地图并进行调试,实际的类没有我从我的测试类传递的密钥。

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]}

     }

 }

我不知道为什么会这样,我做错了什么?任何形式的帮助将不胜感激。

4

1 回答 1

0

你的问题在这里:

Mockito.when(stepContext.getJobExecutionContext()).thenReturn(map);

map不是一个ExecutionContext. 您应该模拟/存根ExecutionContext实例而不是Map<String, Object>实例。你的 tasklet 应该调用:

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

代替:

chunkContext.getStepContext().getJobExecutionContext()
于 2020-05-06T08:02:33.997 回答