如何为 FileInput 模拟 java.util.Scanner

How to Mock java.util.Scanner for a FileInput

我在 CommandLineRunner 中模拟来自 STDIN 方式文件 运行ning 的输入时遇到问题。我已经尝试了几种方法,但每当我 运行 测试时,应用程序都会要求我在命令行中插入文件。

我的命令行class:

@Slf4j
public class CommandLineAppStartupRunner implements CommandLineRunner {
    
    @Autowired
    private AutorizadorService service;

    @Override
    public void run(String...args) throws Exception {
        Scanner scan = new Scanner(System.in);
        log.info("provide file path:");
        service.init(scan.nextLine());
        scan.close();

    }
} ```

MyCommandLineTest class 1 try:

``` @SpringBootTest
public class CommandLineRunnerIntegrationTest {

    @Autowired
    private CommandLineRunner clr;

    @Test
    public void shouldRunCommandLineIntegrationTest1() throws Exception {
        File file = new File("D:/j.json");
        System.setIn(new FileInputStream(file));
        this.clr.run();
    }


    @Test
    public void shouldRunCommandLineIntegrationTest2() throws Exception {
        Scanner mockScanner = mock(Scanner.class);
        when(mockScanner.nextLine()).thenReturn("D:/j.json");
        mockScanner.nextLine();
        verify(mockScanner).nextLine();
    }

    @Test
    public void shouldRunCommandLineIntegrationTest3() throws Exception {
        InputStream in = new ByteArrayInputStream("D:/j.json".getBytes());
        System.setIn(in);
    }

} 

运行 我在命令行中看到的任何测试,只有在我手动输入输入时才会通过

2021-08-21 15:56:36.327  INFO 14772 --- [           main] b.c.a.r.CommandLineAppStartupRunner      : provide file path:

如果您在 run 方法的开头设置断点,您会看到 运行 a @SpringBootTest 实际上运行了该应用程序,即它调用 run 方法在它找到的任何跑步者上。

您应该使用非 springboot 测试来测试 class:

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {CommandLineAppStartupRunner.class})
public class CommandLineRunnerIntegrationTest {

    @Autowired
    private CommandLineRunner clr;

    @Test
    public void shouldRunCommandLineIntegrationTest1() throws Exception {
        System.setIn(getClass().getResourceAsStream("/test.json"));
        this.clr.run();
    }
}

你的 class 稍微简化了:

@Component
public class CommandLineAppStartupRunner implements CommandLineRunner {

    @Override
    public void run(String...args) throws Exception {
        Scanner scan = new Scanner(System.in);
        if (!scan.nextLine().equals("{ \"foo\":  \"bar\"}")) {
            throw new RuntimeException();
        }
        scan.close();
    }
}

您需要在测试 class 上添加 @ContextConfiguration 所需的任何其他配置。