一个工作示例:
在
src/main/java/sandbox/xx中,XX.java。
package sandbox.xx;
import java.io.File;
import java.io.IOException;
class XX {
Process run(final String command) throws IOException {
return this.run(command, null, null);
}
Process run(final String command, final String[] envp) throws IOException {
return this.run(command, envp, null);
}
Process run(final String command, final String[] envp, final File dir) throws IOException {
return Runtime.getRuntime().exec(command, envp, dir);
}
Process run(final String[] cmdarray) throws IOException {
return this.run(cmdarray, null, null);
}
Process run(final String[] cmdarray, final String[] envp) throws IOException {
return this.run(cmdarray, envp, null);
}
Process run(final String[] cmdarray, final String[] envp, final File dir) throws IOException {
return Runtime.getRuntime().exec(cmdarray, envp, dir);
}
}
在
src/test/java/sandbox/xx 中,XXTest.java。
package sandbox.xx;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(XX.class)
public class XXTest {
private static final String TRIGGER_ARG = "some arg";
private static final String EXPECTED_PREFIX = "gotcha!";
private static final String COLON = ": ";
private static final String EXPECTED_RESULT = EXPECTED_PREFIX + COLON + TRIGGER_ARG;
@Test
public void test() throws IOException {
final Runtime mockRuntime = PowerMockito.mock(Runtime.class);
PowerMockito.mockStatic(Runtime.class);
Mockito.when(Runtime.getRuntime()).thenReturn(mockRuntime);
Mockito.when(mockRuntime.exec(ArgumentMatchers.eq(TRIGGER_ARG), ArgumentMatchers.any(), ArgumentMatchers.any())).thenAnswer(invocation -> {
final Process mockProcess = PowerMockito.mock(Process.class);
Mockito.when(mockProcess.toString()).thenReturn(EXPECTED_PREFIX + COLON + invocation.getArguments()[0]);
return mockProcess;
});
final XX xx = new XX();
Assert.assertEquals(EXPECTED_RESULT, xx.run(TRIGGER_ARG).toString());
Assert.assertNull(xx.run("some other arg"));
}
}
希望这能帮到您。