Search code examples
phplaravelunit-testingphpunitlumen

PHPUnit: how to submit raw data to post request linking for testing in Lumen?


I am using the default PHPUnit that comes with Lumen. While I am able to create a mock post call to my link, I am unable to find a way to feed raw data to it.

Currently, to mock up JSON input, from official document, I can:

     $this->json('POST', '/user', ['name' => 'Sally'])
         ->seeJson([
            'created' => true,
         ]);

Or if I want simple form input, I can:

    $this->post('/user', ['name' => 'Sally'])
         ->seeJsonEquals([
            'created' => true,
         ]);

Is there a way I can insert raw body content to the post request? (Or at least a request with XML input? This is a server to receive callback from WeChat, where we have no choice but forced to use XML as WeChat wanted to use.)


Solution

  • As stated in the documentation if you want to create a custom HTTP request you can use the call method:

    If you would like to make a custom HTTP request into your application and get the full Illuminate\Http\Response object, you may use the call method:

    public function testApplication()
    {
        $response = $this->call('GET', '/');
    
        $this->assertEquals(200, $response->status());
    }
    

    Here is the call method:

    public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
    

    So in your case it would be something like this:

    $this->call('POST', '/user', [], [], [], ['Content-Type' => 'text/xml; charset=UTF8'], $xml);
    

    To access the data in your controller you can use the following:

    use Illuminate\Http\Request;
    
    public function store(Request $request)
    {
        $xml = $request->getContent();
        // Or you can use the global request helper
        $xml = request()->getContent();
    }