繁体   English   中英

如何为 FileInput 模拟 java.util.Scanner

[英]How to Mock java.util.Scanner for a FileInput

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

我的命令行 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方法的开头设置断点,您将看到运行@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添加所需的任何其他配置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM