如何在 junit 中编辑作业的执行上下文

how to edit execution context for a job in junit

我能够从 joblaunchertestutils 启动作业并传递作业参数。我也想传递 executioncontext。像这样但它不起作用

@MockBean
JobExecution jobExecution;

@MockBean
ExecutionContext executionContext ;

@MockBean
DownloadDecider downloadDecider;

@MockBean
StepExecution stepExecution;

@BeforeAll
public void setUp() throws Exception {
    
    when(jobExecution.getExecutionContext()).thenReturn(this.executionContext);
    when(jobExecution.getExecutionContext().get(BatchRESULTS)).thenReturn("src/test/r");

@测试 public void testJob() 抛出异常 {

    JobParameters params1 = new JobParameters(setJobParams());
    jobLauncherTestUtils.setJobLauncher(jobLauncher);
    
    
}

@Component("DownloadDecider") public class DownloadDecider 实现 JobExecutionDecider {

Logger logger = LoggerFactory.getLogger(DownloadDecider.class);

@Override
public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) {
    
    System.out.println(stepExecution.getExitStatus().getExitCode());
    System.out.println(jobExecution.getExecutionContext().get(BatchRESULTS));

//打印 null 。该值未通过

您的模拟设置不正确:

when(jobExecution.getExecutionContext()).thenReturn(this.executionContext);
when(jobExecution.getExecutionContext().get(BatchRESULTS)).thenReturn("src/test/r");

您需要先从执行上下文模拟您需要的行为,然后在作业执行时设置它:

when(this.executionContext.get(BatchRESULTS)).thenReturn("src/test/r");
when(jobExecution.getExecutionContext()).thenReturn(this.executionContext);