All Downloads are FREE. Search and download functionalities are using the official Maven repository.

name.didier.david.test4j.utils.CliCaptureJob Maven / Gradle / Ivy

The newest version!
package name.didier.david.test4j.utils;

import static com.google.common.base.Throwables.throwIfUnchecked;

/**
 * Help testing CLI by capture all exit calls and the standard streams. This is a combination of {@link ExitCaptureJob}
 * and {@link StdCaptureJob}. Usage:
 *
 * 
 * new CliCaptureJob() {
 *     @Override
 *     protected void execute() {
 *         doSomethingWithtTheCli();
 *     }
 *
 *     @Override
 *     protected void checkStatus(int status) {
 *         assertThat(status).isEqualTo(-1);
 *     }
 *
 *     @Override
 *     protected void checkCaptures(String stdOutCapture, String stdErrCapture) {
 *         assertThat(stdOutCapture).contains("something");
 *         assertThat(stdErrCapture).contains("something else");
 *     }
 * }.run();
 * 
* * @author ddidier */ public abstract class CliCaptureJob implements Runnable { /** Capture all exit calls. */ private final ExitCaptor exitCaptor = new ExitCaptor(); /** Capture STDOUT and STDERR. */ private final StdCaptor stdCaptor = new StdCaptor(); /** Default constructor. */ protected CliCaptureJob() { super(); } @Override public void run() { try { startCapturing(); execute(); } catch (NoExitException e) { checkStatus(e.getStatus()); } catch (Exception e) { // OK to catch exception here throwIfUnchecked(e); throw new RuntimeException(e); } finally { stopCapturing(); } } /** * Start capturing exit calls, STDOUT and STDERR. */ protected void startCapturing() { exitCaptor.startCapturing(); stdCaptor.startStdErrCapture(); stdCaptor.startStdOutCapture(); } /** * Execute whatever you want to capture. */ protected abstract void execute(); /** * Stop capturing exit calls, STDOUT and STDERR. */ protected void stopCapturing() { String stdOutCapture = stdCaptor.stopStdOutCapture(); String stdErrCapture = stdCaptor.stopStdErrCapture(); exitCaptor.stopCapturing(); checkCaptures(stdOutCapture, stdErrCapture); } /** * Check the captured exit call status. * * @param status the exit status. */ protected abstract void checkStatus(int status); /** * Check the captured streams. * * @param stdOutCapture the captured STDOUT. * @param stdErrCapture the captured STDERR. */ protected abstract void checkCaptures(String stdOutCapture, String stdErrCapture); }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy