Summer Sale! All accounts are 50% off this week.

mstnorris's avatar

phpunit - $this->post fails but $this->json works

I'm implementing an API and writing some tests but I'm running into some issues with the request data (or at least I think so).

  1. I've added some middleware to validate the headers (Content-Type and Accept)
  2. The route is POST only
  3. I validate the request data, one of the items is optional, but when it is present it must be alpha_dash.

In PHPUnit - When using $this->post(...) I satisfy the other parameters, but intentionally fail the optional one (I provide it but it is malformed) the test fails.

However - When I change the test to use $this->json(...) it works. The reason why I don't want to use $this->json(...) is that I want to verify that my middleware works to validate the headers and by using $this->json(...) it always passes.

From what I've read there are some issues around request data and POST routes but I am unable to find a solution.

0 likes
4 replies
mstnorris's avatar

Anyone have any idea on this? I don't believe I am the only one, and a similar (if not the same issue) has been raised when using Lumen too.

thepassenger's avatar

I don't know if this can be any help but in the

Illuminate\Foundation\Testing\Concerns\MakesHttpRequests

trait you can see the json method:

public function json($method, $uri, array $data = [], array $headers = [])
    {
        $files = $this->extractFilesFromDataArray($data);

        $content = json_encode($data);

        $headers = array_merge([
            'CONTENT_LENGTH' => mb_strlen($content, '8bit'),
            'CONTENT_TYPE' => 'application/json',
            'Accept' => 'application/json',
        ], $headers);

        return $this->call(
            $method, $uri, [], [], $files, $this->transformHeadersToServerVars($headers), $content
        );
    }

Perhaps your middleware validation are passing because this is overriding the headers?

mstnorris's avatar

@thepassenger thanks for your reply, but I'm aware of that. What you have pointed out is why I don't want to use the $this->json(...) method. For some tests, sure, this is fine as I'm not testing the headers themselves, but what I'm passing in.

For validating the headers, the $this->post(...) works fine.

My issue is that some tests fail when using the $this->post(...) but pass when using $this->json(...) and I want to know why.

Please or to participate in this conversation.