我无法使用 Spring Batch 测试来模拟调用

问题描述 投票:0回答:1

我正在尝试测试批处理作业的一个步骤,为此我模拟了一个调用

downloadService.downloadFile()
,但是当我运行测试时,调用
downloadService.downloadFile()
只是执行而不是模拟。 我的测试班:

@SpringBootTest
@SpringBatchTest
@ExtendWith(MockitoExtension.class)
public class ImportJobTest2 {

    @Autowired
    private Job importJob;
    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private JobRepository jobRepository;
    @Mock
    private  DownloadService downloadService;



    private JobLauncherTestUtils jobLauncherTestUtils;
    @BeforeEach
      public void initializeJobLauncherTestUtils() {
    MockitoAnnotations.initMocks(this);

    this.jobLauncherTestUtils = new JobLauncherTestUtils();
        this.jobLauncherTestUtils.setJobLauncher(jobLauncher);
        this.jobLauncherTestUtils.setJobRepository(jobRepository);
        this.jobLauncherTestUtils.setJob(importJob);
    }


    @Test
    void import_thenSuccess() throws FileNotFoundException {
        File file = ResourceUtils.getFile("classpath:results.json.zip");
        when(downloadService.downloadFile()).thenReturn(file);

        if (file.exists()) {
            JobExecution jobExecution = jobLauncherTestUtils.launchStep(
                    "download_step1", new JobParameters());
            Collection actualStepExecutions = jobExecution.getStepExecutions();
            ExitStatus actualJobExitStatus = jobExecution.getExitStatus();

            // then
            assertEquals(1, actualStepExecutions.size());
            assertEquals("COMPLETED", actualJobExitStatus.getExitCode());
            // AssertFile.assertFileEquals(expectedResult, actualResult);

        }
    }
}

我想模拟通话的读者:

@RequiredArgsConstructor
public class DownloadItemReader implements ItemStreamReader<String> {
private final File workingDirectory;
private final DownloadService downloadService;


private boolean downloaded = false;

//Single step
@Override
public synchronized String read() throws Exception {
    if (downloaded ) {
        return null;
    }

    var downloadFile = downloadService.downloadFile();

    downloaded = true;
    return "COMPLETE";
}
spring mockito spring-batch junit5
1个回答
0
投票

它应该是@MockBean而不是@Mock

© www.soinside.com 2019 - 2024. All rights reserved.