Skip to content

Commit db6008b

Browse files
authored
Merge pull request eugenp#6388 from JonCook/master
BAEL-2541 - Guide to ProcessBuilder API
2 parents 6258bad + 9838dca commit db6008b

File tree

2 files changed

+220
-0
lines changed

2 files changed

+220
-0
lines changed
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
package com.baeldung.processbuilder;
2+
3+
import static org.hamcrest.Matchers.containsString;
4+
import static org.hamcrest.Matchers.empty;
5+
import static org.hamcrest.Matchers.hasItem;
6+
import static org.hamcrest.Matchers.hasItems;
7+
import static org.hamcrest.Matchers.is;
8+
import static org.hamcrest.Matchers.not;
9+
import static org.junit.Assert.assertEquals;
10+
import static org.junit.Assert.assertThat;
11+
12+
import java.io.BufferedReader;
13+
import java.io.File;
14+
import java.io.IOException;
15+
import java.io.InputStream;
16+
import java.io.InputStreamReader;
17+
import java.lang.ProcessBuilder.Redirect;
18+
import java.nio.file.Files;
19+
import java.util.Arrays;
20+
import java.util.List;
21+
import java.util.Map;
22+
import java.util.concurrent.ExecutionException;
23+
import java.util.stream.Collectors;
24+
25+
import org.junit.Rule;
26+
import org.junit.Test;
27+
import org.junit.rules.TemporaryFolder;
28+
29+
public class ProcessBuilderUnitTest {
30+
31+
@Rule
32+
public TemporaryFolder tempFolder = new TemporaryFolder();
33+
34+
@Test
35+
public void givenProcessBuilder_whenInvokeStart_thenSuccess() throws IOException, InterruptedException, ExecutionException {
36+
ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");
37+
processBuilder.redirectErrorStream(true);
38+
39+
Process process = processBuilder.start();
40+
41+
List<String> results = readOutput(process.getInputStream());
42+
assertThat("Results should not be empty", results, is(not(empty())));
43+
assertThat("Results should contain java version: ", results, hasItem(containsString("java version")));
44+
45+
int exitCode = process.waitFor();
46+
assertEquals("No errors should be detected", 0, exitCode);
47+
}
48+
49+
@Test
50+
public void givenProcessBuilder_whenModifyEnvironment_thenSuccess() throws IOException, InterruptedException {
51+
ProcessBuilder processBuilder = new ProcessBuilder();
52+
Map<String, String> environment = processBuilder.environment();
53+
environment.forEach((key, value) -> System.out.println(key + value));
54+
55+
environment.put("GREETING", "Hola Mundo");
56+
57+
List<String> command = getGreetingCommand();
58+
processBuilder.command(command);
59+
Process process = processBuilder.start();
60+
61+
List<String> results = readOutput(process.getInputStream());
62+
assertThat("Results should not be empty", results, is(not(empty())));
63+
assertThat("Results should contain a greeting ", results, hasItem(containsString("Hola Mundo")));
64+
65+
int exitCode = process.waitFor();
66+
assertEquals("No errors should be detected", 0, exitCode);
67+
}
68+
69+
@Test
70+
public void givenProcessBuilder_whenModifyWorkingDir_thenSuccess() throws IOException, InterruptedException {
71+
List<String> command = getDirectoryListingCommand();
72+
ProcessBuilder processBuilder = new ProcessBuilder(command);
73+
74+
processBuilder.directory(new File("src"));
75+
Process process = processBuilder.start();
76+
77+
List<String> results = readOutput(process.getInputStream());
78+
assertThat("Results should not be empty", results, is(not(empty())));
79+
assertThat("Results should contain directory listing: ", results, hasItems(containsString("main"), containsString("test")));
80+
81+
int exitCode = process.waitFor();
82+
assertEquals("No errors should be detected", 0, exitCode);
83+
}
84+
85+
@Test
86+
public void givenProcessBuilder_whenRedirectStandardOutput_thenSuccessWriting() throws IOException, InterruptedException {
87+
ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");
88+
89+
processBuilder.redirectErrorStream(true);
90+
File log = tempFolder.newFile("java-version.log");
91+
processBuilder.redirectOutput(log);
92+
93+
Process process = processBuilder.start();
94+
95+
assertEquals("If redirected, should be -1 ", -1, process.getInputStream()
96+
.read());
97+
int exitCode = process.waitFor();
98+
assertEquals("No errors should be detected", 0, exitCode);
99+
100+
List<String> lines = Files.lines(log.toPath())
101+
.collect(Collectors.toList());
102+
103+
assertThat("Results should not be empty", lines, is(not(empty())));
104+
assertThat("Results should contain java version: ", lines, hasItem(containsString("java version")));
105+
}
106+
107+
@Test
108+
public void givenProcessBuilder_whenRedirectStandardOutput_thenSuccessAppending() throws IOException, InterruptedException {
109+
ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");
110+
111+
File log = tempFolder.newFile("java-version-append.log");
112+
processBuilder.redirectErrorStream(true);
113+
processBuilder.redirectOutput(Redirect.appendTo(log));
114+
115+
Process process = processBuilder.start();
116+
117+
assertEquals("If redirected output, should be -1 ", -1, process.getInputStream()
118+
.read());
119+
120+
int exitCode = process.waitFor();
121+
assertEquals("No errors should be detected", 0, exitCode);
122+
123+
List<String> lines = Files.lines(log.toPath())
124+
.collect(Collectors.toList());
125+
126+
assertThat("Results should not be empty", lines, is(not(empty())));
127+
assertThat("Results should contain java version: ", lines, hasItem(containsString("java version")));
128+
}
129+
130+
@Test
131+
public void givenProcessBuilder_whenStartingPipeline_thenSuccess() throws IOException, InterruptedException {
132+
if (!isWindows()) {
133+
List<ProcessBuilder> builders = Arrays.asList(
134+
new ProcessBuilder("find", "src", "-name", "*.java", "-type", "f"),
135+
new ProcessBuilder("wc", "-l"));
136+
137+
List<Process> processes = ProcessBuilder.startPipeline(builders);
138+
Process last = processes.get(processes.size() - 1);
139+
140+
List<String> output = readOutput(last.getInputStream());
141+
assertThat("Results should not be empty", output, is(not(empty())));
142+
}
143+
}
144+
145+
@Test
146+
public void givenProcessBuilder_whenInheritIO_thenSuccess() throws IOException, InterruptedException {
147+
List<String> command = getEchoCommand();
148+
ProcessBuilder processBuilder = new ProcessBuilder(command);
149+
150+
processBuilder.inheritIO();
151+
Process process = processBuilder.start();
152+
153+
int exitCode = process.waitFor();
154+
assertEquals("No errors should be detected", 0, exitCode);
155+
}
156+
157+
private List<String> readOutput(InputStream inputStream) throws IOException {
158+
try (BufferedReader output = new BufferedReader(new InputStreamReader(inputStream))) {
159+
return output.lines()
160+
.collect(Collectors.toList());
161+
}
162+
}
163+
164+
private List<String> getDirectoryListingCommand() {
165+
return isWindows() ? Arrays.asList("cmd.exe", "/c", "dir") : Arrays.asList("/bin/sh", "-c", "ls");
166+
}
167+
168+
private List<String> getGreetingCommand() {
169+
return isWindows() ? Arrays.asList("cmd.exe", "/c", "echo %GREETING%") : Arrays.asList("/bin/bash", "-c", "echo $GREETING");
170+
}
171+
172+
private List<String> getEchoCommand() {
173+
return isWindows() ? Arrays.asList("cmd.exe", "/c", "echo hello") : Arrays.asList("/bin/sh", "-c", "echo hello");
174+
}
175+
176+
private boolean isWindows() {
177+
return System.getProperty("os.name")
178+
.toLowerCase()
179+
.startsWith("windows");
180+
}
181+
182+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package org.baeldung.mockito.misusing;
2+
3+
import static org.hamcrest.CoreMatchers.containsString;
4+
import static org.junit.Assert.assertThat;
5+
import static org.junit.jupiter.api.Assertions.fail;
6+
7+
import java.util.ArrayList;
8+
import java.util.List;
9+
10+
import org.junit.After;
11+
import org.junit.Test;
12+
import org.mockito.Mockito;
13+
import org.mockito.exceptions.misusing.NotAMockException;
14+
import org.mockito.internal.progress.ThreadSafeMockingProgress;
15+
16+
public class MockitoMisusingUnitTest {
17+
18+
@After
19+
public void tearDown() {
20+
ThreadSafeMockingProgress.mockingProgress().reset();
21+
}
22+
23+
@Test
24+
public void givenNotASpy_whenDoReturn_thenThrowNotAMock() {
25+
try {
26+
List<String> list = new ArrayList<String>();
27+
28+
Mockito.doReturn(100, Mockito.withSettings().lenient())
29+
.when(list)
30+
.size();
31+
32+
fail("Should have thrown a NotAMockException because 'list' is not a mock!");
33+
} catch (NotAMockException e) {
34+
assertThat(e.getMessage(), containsString("Argument passed to when() is not a mock!"));
35+
}
36+
}
37+
38+
}

0 commit comments

Comments
 (0)