如何从Java中执行newman命令?现有方案报错求替代方法
Java执行Newman报错找不到文件?试试这些方法
系统报错Cannot run program "newman": CreateProcess error=2,本质是找不到newman的可执行文件,大概率是没加入系统PATH,或者Java进程的环境变量没覆盖到,试试下面几种替代执行方式:
1. 用Newman的完整路径执行
先找到你电脑里Newman的实际安装路径,Windows下一般是C:\Users\<你的用户名>\AppData\Roaming\npm\newman.cmd,把命令里的newman换成这个完整路径就行:
Process processObject = Runtime.getRuntime().exec("C:/Users/你的用户名/AppData/Roaming/npm/newman.cmd run 'C:/Dev/config/service-tests/postmanCollections/test.json' -r json,html");
2. 通过CMD来执行(Windows专属)
Windows下直接调用脚本可能有解析问题,借助cmd.exe来执行更稳妥,而且用字符串数组传参能避免空格等坑:
Process processObject = Runtime.getRuntime().exec(new String[]{ "cmd.exe", "/c", "newman run 'C:/Dev/config/service-tests/postmanCollections/test.json' -r json,html" });
3. 用ProcessBuilder控制环境变量
Runtime.exec不够灵活,换成ProcessBuilder可以手动把Newman的路径加到进程环境变量里,确保能找到:
ProcessBuilder pb = new ProcessBuilder("newman", "run", "C:/Dev/config/service-tests/postmanCollections/test.json", "-r", "json,html"); // 把系统PATH和Newman路径合并,加到进程环境里 pb.environment().put("PATH", pb.environment().get("PATH") + ";C:/Users/你的用户名/AppData/Roaming/npm"); Process processObject = pb.start();
4. 直接用Node.js调用Newman脚本
如果知道Newman的核心js脚本位置(比如C:\Users\<你的用户名>\AppData\Roaming\npm\node_modules\newman\bin\newman.js),直接用node命令启动它:
Process processObject = Runtime.getRuntime().exec("node C:/Users/你的用户名/AppData/Roaming/npm/node_modules/newman/bin/newman.js run 'C:/Dev/config/service-tests/postmanCollections/test.json' -r json,html");
内容的提问来源于stack exchange,提问作者Joshcampbell7
相关产品推荐
相关产品推荐

