2

I am learning Laravel 5.4, Still new to Laravel and PHPUnit. Everything is working great after following online basic tutorial.

This test function is working correctly when run phpunit

public function testBasicExample()
{
    $response = $this->call( 'GET' , '/welcome');

    $this->assertTrue(strpos($response->getContent(), 'Laravel') !== false);

}

Problem comes when I try to test Api

Steps I took

  1. Create Api route for books

  2. Return all users from users talbe as json from localhost/api/books/

public function index()
{
  $users = DB::table('users')->get()->toJson();
  echo $users;
}
  1. I open the link in browser and json is returned correctly

  2. copy and pasted json into online json validator jsonlint and it is valid.

  3. Create a new test function

public function test_index_method_returns_all_books()
{
    $response = $this->call( 'GET' , '/api/books/');
      $this->assertEquals(200, $response->getStatusCode()); 

    $data = json_decode($response->getContent(),true);
    $this->assertJson($data);
}
  1. run phpunit 200 status test passed but assertJson did not pass.

  2. I tried to do var_dump for $response->getContent() and found out it return empty.

now I am not able to get getContent() for api/book/. Does anyone know if there is a solution for this?

Thanks.

Here is a screenshot

1
  • I am having similar issue where the curl call returns proper JSON response in the content, but an API call shows the class object information in public $original but the public $content is '{}'. Did you find a resolution to this? Commented Apr 17, 2018 at 15:23

1 Answer 1

0

Try create some data with a factory before you call the api:

e.g.:

factory(\App\Books::class, 20)->create();

then

$response = $this->call( 'GET' , '/api/books/');

If you had set ":memory:" as your database on phpunit.xml, you will no longer see any data from your local database, that's why you should use factory instead.

Sign up to request clarification or add additional context in comments.

Comments

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.