Search code examples
javaspringjunitspring-shell

How to run Spring Shell scripts in a JUnit test


I have a Spring Shell-based application and a couple of scripts. Is there an easy way to run the scripts in a JUnit test such that a test fails, if some exception/error occurs during the execution of the script?

The purpose of the tests is to make sure that all correct scripts run without errors.

Update 1:

Here's a little helper class for running scripts in JUnit:

import org.apache.commons.io.FileUtils;
import org.springframework.shell.Bootstrap;
import org.springframework.shell.core.CommandResult;
import org.springframework.shell.core.JLineShellComponent;

import java.io.File;
import java.io.IOException;
import java.util.List;

import static org.fest.assertions.api.Assertions.*;

public class ScriptRunner {
  public void runScript(final File file) throws IOException 
  {
    final Bootstrap bootstrap = new Bootstrap();
    final JLineShellComponent shell = bootstrap.getJLineShellComponent();

    final List<String> lines = FileUtils.readLines(file);
    for (final String line : lines) {
      execVerify(line, shell);
    }   
  }
  private void execVerify(final String command, final JLineShellComponent shell) {
    final CommandResult result = shell.executeCommand(command);
    assertThat(result.isSuccess()).isTrue();
  }

}

Solution

  • You can create an instance of Bootstrap, get the shell out of it and then executeCommand() (including the shell command) on it.

    You may be interested in what is done in Spring XD for this: https://github.com/spring-projects/spring-xd/blob/master/spring-xd-shell/src/test/java/org/springframework/xd/shell/AbstractShellIntegrationTest.java (although there are a lot of XD specific details)