Spring batch:Test case for Tasklet - Key is not appearing in actual class when it is invoked from Test class

半腔热情 提交于 2020-05-17 05:59:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!