I am trying to mock the constructor for ProcessBuilder. The problem is that when the constructor is called it return null.
Class code:
public static void enable() throws IOException, InterruptedException {
logger.info("Enable NTP server...");
String ntpAddress = AppConfig.getInstance().getString(AppConfig.NTP_SERVER, "");
AppConfig.getInstance().getBoolean(AppConfig.NTP_ENABLED, true);
String enableNtp = "chkconfig ntpd on " + SEPARATOR + " service ntpd stop " + SEPARATOR + " ntpdate " + ntpAddress + " " + SEPARATOR + " service ntpd start";
String[] commandArr = {"bash", "-c", enableNtp};
ProcessBuilder pb = new ProcessBuilder(commandArr);
pb.redirectErrorStream(true);
Process proc = pb.start();
try (BufferedReader in = new BufferedReader(new InputStreamReader(
proc.getInputStream()))) {
String line;
while ((line = in.readLine()) != null) {
logger.info(line);
}
} catch (IOException ex) {
logger.log(Level.SEVERE, "Error while trying to enable NTP Server");
}
proc.waitFor();
proc.destroy();
logger.info("NTP server has been enabled");
}
Test code:
@RunWith(PowerMockRunner.class)
@PrepareForTest({NtpServerUtil.class, ProcessBuilder.class})
public class NtpServerUtilTest extends AbstractDbTest {
@Test
public void testEnableNtp() throws Exception {
ProcessBuilder pb = PowerMockito.mock(ProcessBuilder.class);
PowerMockito.whenNew(ProcessBuilder.class).withAnyArguments().thenReturn(pb);
NtpServerUtil.enable();
PowerMockito.verifyNew(ProcessBuilder.class).withArguments(Matchers.anyString());
}
}
So, when it goes for new ProcessBuilder(command), the result is null. After that, when processBuilder.start() is called an exception is thrown. I tried some methods for mocking that constructor. Any ideas, please?