测试
Spring Shell 提供了多个实用工具来简化壳应用程序的测试。这些实用工具帮助模拟用户输入,捕获输出,并在受控环境中验证命令行为。
测试断言
Spring Shell 提供以下测试断言 API 以验证命令执行和输出:
-
ShellScreen: 这个类代表控制台屏幕,并允许您捕获和分析显示给用户的输出。 -
ShellAssertions: 该类提供了静态方法来断言shell命令执行的结果。 -
ShellTestClient: 此类允许您模拟用户输入并程序化执行Shell命令。
这里是如何在测试中使用这些API的一个示例:<br/>
@ExtendWith(SpringExtension.class)
class ShellTestClientTests {
@Test
void testCommandExecution(@Autowired ShellTestClient shellTestClient) throws Exception {
// when
ShellScreen shellScreen = shellTestClient.sendCommand("test");
// then
ShellAssertions.assertThat(shellScreen).containsText("Test command executed");
}
}
测试注解
Spring Shell 提供了 @ShellTest 注解,用于表示一个测试类是 Spring Shell 测试。它会设置测试 shell 命令所需的上下文。此注解定义在 spring-shell-test-autoconfigure 模块中,并且设计用于与 Spring Boot 应用程序一起使用。
一旦您定义了Spring Boot应用程序类,就可以创建一个用@SpringBootTest注解的测试类来测试您的命令行操作。以下是一个示例:
@SpringBootApplication
public class ExampleShellApplication {
@Command(name = "hi", description = "Says hello")
public String hello() {
return "hello";
}
}
@ShellTest
@ContextConfiguration(classes = ExampleShellApplication.class)
class ShellTestIntegrationTests {
@Test
void testCommandExecution(@Autowired ShellTestClient client) throws Exception {
// when
ShellScreen shellScreen = client.sendCommand("hi");
// then
ShellAssertions.assertThat(shellScreen).containsText("hello");
}
@Test
void testUnknownCommandExecution(@Autowired ShellTestClient client) {
Assertions.assertThatThrownBy(() -> client.sendCommand("foo"))
.isInstanceOf(CommandNotFoundException.class);
}
}
端到端测试
对于不使用Spring Shell测试设施的shell应用程序的端到端(即黑盒)测试,您可以使用Spring Boot提供的测试工具。一旦您定义了Spring Boot应用类,就可以创建一个带有@ContextConfiguration注解的测试类来测试您的shell命令。以下是一个示例:
@SpringBootApplication
public class MyShellApplication {
public static void main(String[] args) {
SpringApplication.run(MyShellApplication.class, args);
}
@Command
public void hi() {
System.out.println("Hello world!");
}
}
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE,
useMainMethod = SpringBootTest.UseMainMethod.ALWAYS,
classes = { MyShellApplication.class },
properties = { "spring.shell.interactive.enabled=false" },
args = "hi")
@ExtendWith(OutputCaptureExtension.class)
public class ShellApplicationEndToEndTests {
@Test
void testCommandOutput(CapturedOutput output) {
assertThat(output).contains("Hello world!");
}
}
这个示例演示了如何在测试上下文中运行一个Spring Shell应用程序,并使用Spring Boot的OutputCaptureExtension验证命令输出。