11. Testing

Testing cli application is difficult due to various reasons:spring-doc.cn

  • There are differences between OS’s.spring-doc.cn

  • Within OS there may be different shell implementations in use.spring-doc.cn

  • What goes into a shell and comes out from a shell my be totally different what you see in shell itself due to control characters.spring-doc.cn

  • Shell may feel syncronous but most likely it is not meaning when someting is written into it, you can’t assume next update in in it is not final.spring-doc.cn

Testing support is currently under development and will be unstable for various parts.

11.1. Basics

Spring Shell provides a number of utilities and annotations to help when testing your application. Test support is provided by two modules: spring-shell-test contains core items, and spring-shell-test-autoconfigure supports auto-configuration for tests.spring-doc.cn

To test interactive commands.spring-doc.cn

@ShellTest
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
class InteractiveTestSample {

	@Autowired
	ShellTestClient client;

	@Test
	void test() {
		InteractiveShellSession session = client
				.interactive()
				.run();

		await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> {
			ShellAssertions.assertThat(session.screen())
				.containsText("shell");
		});

		session.write(session.writeSequence().text("help").carriageReturn().build());
		await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> {
			ShellAssertions.assertThat(session.screen())
				.containsText("AVAILABLE COMMANDS");
		});
	}
}

To test non-interactive commands.spring-doc.cn

@ShellTest
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
class NonInteractiveTestSample {

	@Autowired
	ShellTestClient client;

	@Test
	void test() {
		NonInteractiveShellSession session = client
			.nonInterative("help", "help")
			.run();

		await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> {
			ShellAssertions.assertThat(session.screen())
				.containsText("AVAILABLE COMMANDS");
		});
	}
}

11.2. Settings

Built in emulation uses terminal width 80 and height 24 on default. Changing dimensions is useful if output would span into multiple lines and you don’t want to handle those cases in a tests.spring-doc.cn

These can be changed using properties spring.shell.test.terminal-width or spring.shell.test.terminal-height.spring-doc.cn

@ShellTest(properties = {
	"spring.shell.test.terminal-width=120",
	"spring.shell.test.terminal-height=40"
})
class ShellSettingsSample {}

ShellTest annotation have fields terminalWidth and terminalHeight which can also be used to change dimensions.spring-doc.cn

@ShellTest(terminalWidth = 120, terminalHeight = 40)
class ShellSettingsSample {}