3

I have a route that does a POST to create data and I'm trying to test if everything should be working the way it should be.

I have a json string that will have the values that i want to test but so far the test is always failing when I run the test using phpunit:

Also,I know the json string is just a string but I'm also unsure of how to use the json string to test for input.

my route:

Route::post('/flyer', 'flyersController@store');

 public function testFlyersCreation()
{
    $this->call('POST', 'flyers');

    //Create test json string
    $json = '{ "name": "Test1", "email": "[email protected]", "contact": "11113333" }';

    var_dump(json_decode($json));



}

When i run phpunit, my error points to the call POST that says "undefined index: name"

2 Answers 2

1

I'm not sure if i understand the question correctly, given the code example that actually does nothing, but if you're asking how to test a post route which requires json data in the request, take a look at the call() method:

https://github.com/laravel/framework/blob/4.2/src/Illuminate/Foundation/Testing/ApplicationTrait.php

raw post data should be in the $content variable.

I don't have Laravel 4 installed to test it, but it works for me in Laravel 5, where the function has just slightly different order of params:

public function testCreateUser()
{
    $json = '
    {
        "email" : "[email protected]",
        "first_name" : "Horst",
        "last_name" : "Fuchs"
    }';

    $response = $this->call('POST', 'user/create', array(), array(), array(), array(), $json);

    $this->assertResponseOk();
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you look at the source code of TestCase you can see that the method is actually calling

call_user_func_array(array($this->client, 'request'), func_get_args());

So this means you can do something like this

$this->client->request('POST', 'flyers', $json );

and then you check the response with

$this->assertEquals($json, $this->client->getResponse());

The error you are getting is probably thrown by the controller because it doesnt receive any data

2 Comments

hmm, I tried this and inside the request of $json, I input a decoded $json string and it's asking for an array but when I change it into an array, it asks for a string.
hm ok, the $client is api.symfony.com/2.0/Symfony/Component/HttpKernel/Client.html. So try it like so $this->client->request('POST', 'flyers', null, null, null, $json);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.