使用Plug.Test无法发送JSON的问题咨询(附代码示例)
Let's break down why your test might be misbehaving and fix it step by step.
The Root Problem: Missing Content-Type Header
Your test sends raw JSON data but doesn't set the Content-Type header to application/json. The Plug.Parsers with the :json parser only activates when it detects this specific header—without it, Plug won't parse the JSON body into conn.params, which is almost certainly causing issues in your handler logic.
Fix 1: Update Your Test to Include the Correct Header
Modify your test to add the required header before calling your Plug. Here's the adjusted version:
test "Welcomes Github" do payload = %{repository: %{full_name: "test/test"}} conn = conn(:post, "/", Jason.encode!(payload)) |> put_req_header("content-type", "application/json") |> Web.call([]) assert conn.state == :sent assert conn.status == 200 end
Fix 2: Simplify with Plug.Conn.json/2 (Optional but Cleaner)
You can skip manual JSON encoding and header setting entirely by using Plug.Conn.json/2, which handles both tasks for you:
test "Welcomes Github" do payload = %{repository: %{full_name: "test/test"}} conn = conn(:post, "/", "") |> json(payload) |> Web.call([]) assert conn.state == :sent assert conn.status == 200 end
Double-Check Your Plug's call Function
Make sure your call function is complete and properly handles the request. A minimal working example would look like this:
defmodule MrsNorris.Web do import Plug.Conn use Plug.Builder plug Plug.Parsers, parsers: [:json], pass: ["*/*"], json_decoder: Jason def init(options), do: options def call(conn, _opts) do # Access parsed JSON data via conn.params here IO.inspect(conn.params, label: "Parsed Request Params") conn |> put_resp_content_type("application/json") |> send_resp(200, Jason.encode!(%{status: "success"})) end end
Quick Verification
After making these changes, run your test again. The Plug.Parsers should now correctly parse the JSON body into conn.params, and your Plug will handle the request as expected.
内容的提问来源于stack exchange,提问作者ngw

