简体   繁体   中英

Laravel 5.1 PHPUnit Tests for API using JSON

I just started working with Unit testing in Laravel 5.1 to test an API I'm building, and I can get PHPUnit to work fine with the ExampleTest.php, but when I create my own test, it fails every time.

Here is the response for my API endpoint v1/conversations :

{
  "data": [
    {
      "id": 1,
      "created_at": "2015-07-05",
      "updated_at": "2015-07-07"
    },
    {
      "id": 2,
      "created_at": "2015-07-06",
      "updated_at": "2015-07-08"
    }
  ]
}

Here is my ConversationsTest.php:

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ConversationsTest extends TestCase
{

    public function test_list_conversations()
    {
        $this->get('v1/conversations')->seeJson('data');
    }
}

But when I got to run my test, I get the following:

There was 1 error:

1) ConversationsTest::test_list_conversations
ErrorException: Argument 1 passed to Illuminate\Foundation\Testing\TestCase::seeJson() must be of the type array, string given

Isn't my API returning valid JSON data? Why can't Laravel's seeJson method interpret the response? I've tried to follow the Laravel 5.1 Testing APIs documentation , but I'm clearly missing something...

The data returned by your endpoint is fine and should not be modified. The error is simply telling you that you are passing a string into the function seeJson('data');

According to this here, https://github.com/laracasts/Integrated/wiki/Testing-APIs , you should be able to use it like so just to verify that some JSON is being returned...

$this->get('v1/conversations')->seeJson();

You can also pass in an array to this function to see if a certain part of the data exists...

$this->get('v1/conversations')->seeJson([
    'data' => 'some data',
]);

Though that will likely fail unless you pass in the entire array which is also being returned by your endpoint.

The only thing you can not do is pass in a string to this function as it wouldn't know what to do with a string.

Try this

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ConversationsTest extends TestCase
{

    public function test_list_conversations()
    {
        $this->get('v1/conversations')->seeJson(['data']);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM