テスト
Spring Shell は、シェルアプリケーションのテストを容易にするためのユーティリティをいくつか提供しています。これらのユーティリティは、ユーザー入力のシミュレーション、出力のキャプチャー、制御された環境でのコマンド動作の検証に役立ちます。
テストアサーション
Spring Shell は、コマンドの実行と出力を検証するための次のテストアサーション API を提供します。
ShellScreen: このクラスはシェル画面を表し、ユーザーに表示される出力をキャプチャーして分析することができます。ShellAssertions: このクラスは、シェルコマンド実行の結果をアサートするための静的メソッドを提供します。ShellTestClient: このクラスを使用すると、ユーザー入力をシミュレートし、シェルコマンドをプログラムで実行できます。
これらの API をテストで使用する方法の例を次に示します。
@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 は、テストクラスが Spring Shell テストであることを示すために用いられる @ShellTest アノテーションを提供します。これは、シェルコマンドのテストに必要なコンテキストを設定します。このアノテーションは spring-shell-test-autoconfigure モジュールで定義されており、Spring Boot アプリケーションで使用するように設計されています。
Spring Boot アプリケーションクラスを定義したら、@ShellTest アノテーションを付与したテストクラスを作成して、シェルコマンドをテストできます。以下に例を示します。
@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);
}
}