Powermock:ProcessBuilder redirectErrorStream 给出 nullPointerException

发布于 2024-09-01 03:57:58 字数 3299 浏览 6 评论 0原文

我正在使用 powermock 使用进程生成器来模拟一些本机命令调用。奇怪的是这些测试有时会通过,有时会失败,给出 NPE。这是 powermock 问题还是程序中的一些问题。

这是我正在测试的类的片段:

public void method1(String jsonString, String filename) {
  try {
    JSONObject jObj = new JSONObject(jsonString);
    JSONArray jArr = jObj.getJSONArray("something");

    String cmd = "/home/y/bin/perl <perlscript>.pl<someConstant>" + " -k " + <someConstant> + " -t " + <someConstant>;

    cmd += vmArr.getJSONObject(i).getString("jsonKey");

    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(false);
    Process shell = pb.start();
    shell.waitFor();
    if (shell.exitValue() != 0) {
      throw new RuntimeException("Error in Collecting the logs. cmd="+cmd);
    }
    StringBuilder error = new StringBuilder();
    InputStream iError = shell.getErrorStream();
    BufferedReader bfr =
      new BufferedReader(
      new InputStreamReader(iError));
    String line = null;
    while ((line = bfr.readLine()) != null) {
      error.append(line + "\n");
    }
    if (!error.toString().isEmpty()) {
      LOGGER.error(error`enter code here`);
    }
    iError.close();
    bfr.close();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

单元测试用例是:

@PrepareForTest( {<Classtobetested>.class, ProcessBuilder.class,Process.class, InputStream.class,InputStreamReader.class, BufferedReader.class} )
@Test(sequential=true)
public class TestClass {

@Test(groups = {"unit"})
public void testMethod() {
  try {
    ProcessBuilder prBuilderMock = createMock(ProcessBuilder.class);
    Process processMock = createMock(Process.class);
    InputStream iStreamMock = createMock(InputStream.class);
    InputStreamReader iStrRdrMock = createMock(InputStreamReader.class);
    BufferedReader bRdrMock = createMock(BufferedReader.class);
    String errorStr =" Error occured";

    String json = <jsonStringInput>;
    String cmd = "/home/y/bin/perl <perlscript>.pl -k "+<someConstant>+" -t "+<someConstant>+" "+<jsonValue>;

    expectNew(ProcessBuilder.class, "bash", "-c", cmd).andReturn(prBuilderMock);
    expect(prBuilderMock.redirectErrorStream(false)).andReturn(prBuilderMock);
    expect(prBuilderMock.start()).andReturn(processMock);
    expect(processMock.waitFor()).andReturn(0);
    expect(processMock.exitValue()).andReturn(0);
    expect(processMock.getErrorStream()).andReturn(iStreamMock);
    expectNew(InputStreamReader.class, iStreamMock)
                .andReturn(iStrRdrMock);
    expectNew(BufferedReader.class, iStrRdrMock)
                .andReturn(bRdrMock);
    expect(bRdrMock.readLine()).andReturn(errorStr);
    expect(bRdrMock.readLine()).andReturn(null);
    iStreamMock.close();
    bRdrMock.close();
    expectLastCall().once();
    replayAll();
    <ClassToBeTested> instance = new <ClassToBeTested>();
    instance.method1(json, fileName);
    verifyAll();
  } catch (Exception e) {
    Assert.fail("failed while collecting log.", e);
  }
}

我在执行时收到错误,测试用例失败。

Caused by: java.lang.NullPointerException
at java.lang.ProcessBuilder.start(ProcessBuilder.java:438)

注意:我在所有执行中都没有收到此错误。有时会通过,有时会失败。我无法理解这种行为。另外,由于版权问题,我伪装了一些变量名称。

I am using powermock to mock some native command invocation using process builder. the strange thing is these test pass sometimes and fail sometimes giving a NPE. Is this a powermock issue or some gotcha in the program.

Here is a snippet of the class I am testing:

public void method1(String jsonString, String filename) {
  try {
    JSONObject jObj = new JSONObject(jsonString);
    JSONArray jArr = jObj.getJSONArray("something");

    String cmd = "/home/y/bin/perl <perlscript>.pl<someConstant>" + " -k " + <someConstant> + " -t " + <someConstant>;

    cmd += vmArr.getJSONObject(i).getString("jsonKey");

    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(false);
    Process shell = pb.start();
    shell.waitFor();
    if (shell.exitValue() != 0) {
      throw new RuntimeException("Error in Collecting the logs. cmd="+cmd);
    }
    StringBuilder error = new StringBuilder();
    InputStream iError = shell.getErrorStream();
    BufferedReader bfr =
      new BufferedReader(
      new InputStreamReader(iError));
    String line = null;
    while ((line = bfr.readLine()) != null) {
      error.append(line + "\n");
    }
    if (!error.toString().isEmpty()) {
      LOGGER.error(error`enter code here`);
    }
    iError.close();
    bfr.close();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

and the unit test case is:

@PrepareForTest( {<Classtobetested>.class, ProcessBuilder.class,Process.class, InputStream.class,InputStreamReader.class, BufferedReader.class} )
@Test(sequential=true)
public class TestClass {

@Test(groups = {"unit"})
public void testMethod() {
  try {
    ProcessBuilder prBuilderMock = createMock(ProcessBuilder.class);
    Process processMock = createMock(Process.class);
    InputStream iStreamMock = createMock(InputStream.class);
    InputStreamReader iStrRdrMock = createMock(InputStreamReader.class);
    BufferedReader bRdrMock = createMock(BufferedReader.class);
    String errorStr =" Error occured";

    String json = <jsonStringInput>;
    String cmd = "/home/y/bin/perl <perlscript>.pl -k "+<someConstant>+" -t "+<someConstant>+" "+<jsonValue>;

    expectNew(ProcessBuilder.class, "bash", "-c", cmd).andReturn(prBuilderMock);
    expect(prBuilderMock.redirectErrorStream(false)).andReturn(prBuilderMock);
    expect(prBuilderMock.start()).andReturn(processMock);
    expect(processMock.waitFor()).andReturn(0);
    expect(processMock.exitValue()).andReturn(0);
    expect(processMock.getErrorStream()).andReturn(iStreamMock);
    expectNew(InputStreamReader.class, iStreamMock)
                .andReturn(iStrRdrMock);
    expectNew(BufferedReader.class, iStrRdrMock)
                .andReturn(bRdrMock);
    expect(bRdrMock.readLine()).andReturn(errorStr);
    expect(bRdrMock.readLine()).andReturn(null);
    iStreamMock.close();
    bRdrMock.close();
    expectLastCall().once();
    replayAll();
    <ClassToBeTested> instance = new <ClassToBeTested>();
    instance.method1(json, fileName);
    verifyAll();
  } catch (Exception e) {
    Assert.fail("failed while collecting log.", e);
  }
}

I get an error on execution and the test case fails..

Caused by: java.lang.NullPointerException
at java.lang.ProcessBuilder.start(ProcessBuilder.java:438)

Note: I do not get this error on all executions. Sometimes it passes and sometimes it fails. I am not able to understand this behavior. Also, I have camouflaged some variable names because of the copyright issues.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

终陌 2024-09-08 03:57:58

由于您正在模拟构造函数调用,因此您必须将代码准备为 wall.这是因为构造函数调用是代码的一部分。请阅读 PowerMock 文档了解更多信息:
http://code.google.com/p/powermock/wiki/MockConstructor

Since your are mocking the constructor call you have to prepare your code as wall. This is because the constructor invocation is part of your code. Read more in the PowerMock documentation:
http://code.google.com/p/powermock/wiki/MockConstructor

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文