使用Rest Assured和Cucumber编写Post请求时设置Header出现NPE
Hey, let's break down why that NullPointerException (NPE) is hitting you at line 76 of SalesCRM.java—it's a classic easy-to-miss issue, and the fix is straightforward.
The Root Cause
Looking at your code, you've declared the headers HashMap but never initialized it before trying to call put() on it:
HashMap <String, String> headers; // Only declared, not assigned to a new HashMap instance JSONObject payload = new JSONObject(); BigInteger endPlacementTimestamp = new BigInteger("1593611640000"); BigInteger startPlacementTimestamp = new BigInteger("1594216440000"); payload.put("endPlacementTimestamp",endPlacementTimestamp ); payload.put("startPlacementTimestamp",startPlacementTimestamp); headers.put("authorization","Bearer cd70f469-b963-48f1-9486-fe5d5e3c443b");// line76 - headers is NULL here! response = (Response) AuxiliarMethods.postRequest(url,values,headers,"application/json",payload.toJSONString());
At line 76, headers is still null because you haven't created a new HashMap object for it. Calling any method on a null reference throws an NPE, which exactly matches your stack trace:
java.lang.NullPointerException
at locustTask.SalesCRM.execute(SalesCRM.java:76)
at com.github.myzhan.locust4j.AbstractTask.run(AbstractTask.java:63)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Fix the Issue
All you need to do is initialize the headers HashMap when you declare it:
// Initialize headers to a new HashMap instance HashMap <String, String> headers = new HashMap<>(); JSONObject payload = new JSONObject(); BigInteger endPlacementTimestamp = new BigInteger("1593611640000"); BigInteger startPlacementTimestamp = new BigInteger("1594216440000"); payload.put("endPlacementTimestamp",endPlacementTimestamp ); payload.put("startPlacementTimestamp",startPlacementTimestamp); headers.put("authorization","Bearer cd70f469-b963-48f1-9486-fe5d5e3c443b");// No more NPE here! response = (Response) AuxiliarMethods.postRequest(url,values,headers,"application/json",payload.toJSONString());
Optional Quick Tip
If you ever switch to using Rest Assured's native API directly instead of your helper method, you can simplify header handling with its fluent syntax:
given() .header("authorization", "Bearer cd70f469-b963-48f1-9486-fe5d5e3c443b") .contentType("application/json") .body(payload.toJSONString()) .when() .post(url) .then() // Add assertions or response handling here ;
内容的提问来源于stack exchange,提问作者Sayen

