Shell { public Result exec(String... command) { try { List<String> commandWithShell = new ArrayList<>(); commandWithShell.add("sh"); commandWithShell.add("-c"); commandWithShell.addAll(Arrays.asList(command)); ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.command(commandWithShell); Process process = processBuilder.start(); StringBuilder output = new StringBuilder(); StringBuilder error = new StringBuilder(); StreamGobbler streamGobblerOutput = new StreamGobbler(process.getInputStream(), output::append); StreamGobbler streamGobblerError = new StreamGobbler(process.getErrorStream(), error::append); Thread threadInput = new Thread(streamGobblerOutput); Thread threadOutput = new Thread(streamGobblerError); threadInput.start(); threadOutput.start(); process.waitFor(); threadInput.join(); threadOutput.join(); return new Result(process.exitValue(), output.toString(), error.toString()); } catch (Exception e) { throw new RuntimeException("Can't run shell", e); } }  Result exec(String... command);  }
@Test public void success() { Shell shell = new Shell(); Result result = shell.exec("echo 'coucou'"); assertEquals("coucou", result.getOutput()); assertEquals("", result.getError()); assertEquals(0, result.getExitCode()); }
@Test public void failure() { Shell shell = new Shell(); Result result = shell.exec( "doesnotexistfailure"); assertEquals("", result.getOutput()); assertTrue(result.getError().contains("doesnotexistfailure") && result.getError().contains("not found")); assertEquals(127, result.getExitCode()); }