ShellCommandUtils { public String executeCommand(String command) { Writer output = new StringWriter(); try { Process p = Runtime.getRuntime().exec(command); p.waitFor(); IOUtils.copy(p.getInputStream(), output); } catch (IOException | InterruptedException e) { logger.error(String.format("An error happened while executing command[%s]", command), e); } return output.toString(); }  String executeCommand(String command);  }
@Test public void executeCommandTest() throws IOException, InterruptedException{ Process processMock = Mockito.mock(Process.class); Runtime runtimeMock = configureAndGetRuntimeMock(); String commandOutput = "TEST"; InputStream input = IOUtils.toInputStream(commandOutput, (String) null); Mockito.when(runtimeMock.exec(command)).thenReturn(processMock); Mockito.when(processMock.waitFor()).thenReturn(1); Mockito.when(processMock.getInputStream()).thenReturn(input); String response = spy.executeCommand(command); Assert.assertEquals(commandOutput, response); Mockito.verify(processMock).waitFor(); }
@Test @SuppressWarnings("unchecked") public void executeCommandTestDealingWithIoException() throws IOException, InterruptedException { spy.logger = Mockito.mock(Logger.class); Runtime runtimeMock = configureAndGetRuntimeMock(); Mockito.when(runtimeMock.exec(command)).thenThrow(IOException.class); String commandOutput = spy.executeCommand(command); executeChecksForExceptionTests(commandOutput, IOException.class); }
@Test @SuppressWarnings("unchecked") public void executeCommandTestDealingWithInterruptedException() throws IOException, InterruptedException { spy.logger = Mockito.mock(Logger.class); Process processMock = Mockito.mock(Process.class); Runtime runtimeMock = configureAndGetRuntimeMock(); Mockito.when(runtimeMock.exec(command)).thenReturn(processMock); Mockito.when(processMock.waitFor()).thenThrow(InterruptedException.class); String commandOutput = spy.executeCommand(command); Mockito.verify(processMock).waitFor(); executeChecksForExceptionTests(commandOutput, InterruptedException.class); }