如何为FileInput模拟java.util.Scanner



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

我的命令行类:

@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测试来测试该类:

@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();
}
}

你的类稍微简化了:

@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();
}
}

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

相关内容

最新更新