Postman集合在客户端运行正常全部测试通过,使用Newman命令行执行时全部测试失败
Hey there, let’s walk through why your Newman run is throwing errors even though your Postman collection passes all tests. These issues are super common when moving from the Postman GUI to the command line—here’s how to fix each one:
1. getaddrinfo ENOTFOUND {{baseurl}} Error
This is the root cause of most of your other problems. Postman uses environment/collection variables to replace {{baseurl}}, but Newman doesn’t automatically pick these up unless you explicitly tell it where to find them.
Fixes:
- Export your Postman environment: If you’re using an environment in Postman to define
baseurl, go to the Environments tab, select your environment, and click "Export" to save it as anenv.jsonfile. - Run Newman with the environment file: Use the
-eflag to point Newman to your environment file:newman run collection.json -e env.json - Or pass the variable directly: If you don’t want to use an environment file, use the
--env-varflag to setbaseurlon the fly:newman run collection.json --env-var baseurl=https://your-real-api-url.com
2. Assertion Failure: Expected Object to Contain 'code' Property
This error happens because your request failed (thanks to the baseurl issue), so the response isn’t the JSON object your test expects. Once you fix the baseurl problem and the request returns a valid response, this assertion will likely pass.
To make your tests more robust (and catch these issues earlier), add a check to ensure the response is valid JSON before asserting properties:
pm.test("Response is valid JSON", function () { pm.response.to.be.json; }); pm.test("Response includes 'code' property", function () { const responseData = pm.response.json(); pm.expect(responseData).to.have.property('code'); });
3. Unexpected token u in JSON at position 0 Error
This is another side effect of the failed request. When your request can’t reach the server (because baseurl is missing), the response body is empty or undefined. When your test tries to parse it with pm.response.json(), it’s trying to parse undefined—which starts with the letter "u", hence the error.
Fixing the baseurl issue will resolve this, but you can also add a guard clause in your test to handle failed requests gracefully:
pm.test("Request succeeded", function () { pm.response.to.have.status(200); // Or whatever success status you expect });
Final Steps
- First, confirm your
baseurlis correctly passed to Newman using either an environment file or the--env-varflag. - Run Newman again—if the requests succeed, the other errors should disappear.
- If you still have assertion issues, double-check that your API returns the exact JSON structure your tests expect (sometimes there are subtle differences between local/CI environments).
内容的提问来源于stack exchange,提问作者user14551704

