【问题标题】:phpunit getContent return emptyphpunit getContent 返回空
【发布时间】:2017-08-13 19:13:40
【问题描述】:

我正在学习 Laravel 5.4,对 Laravel 和 PHPUnit 还是很陌生。遵循在线基础教程后,一切正常。

这个测试函数在运行 phpunit 时工作正常

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

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

}

当我尝试测试 Api 时出现问题

我采取的步骤

  1. 为书籍创建 Api 路由

  2. 从 localhost/api/books/ 以 json 形式返回 users talbe 中的所有用户

public function index()
{
  $users = DB::table('users')->get()->toJson();
  echo $users;
}
  1. 我在浏览器中打开链接,json正确返回

  2. 将json复制粘贴到在线json验证器jsonlint中即可。

  3. 创建新的测试函数

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. 运行 phpunit 200 状态测试通过但 assertJson 没有通过。

  2. 我尝试为 $response->getContent() 执行 var_dump,发现它返回空。

现在我无法获取 api/book/ 的 getContent()。有谁知道这个有没有解决办法?

谢谢。

Here is a screenshot

【问题讨论】:

  • 我遇到了类似的问题,即 curl 调用在内容中返回正确的 JSON 响应,但 API 调用在公共 $original 中显示类对象信息,但公共 $content 是“{}”。你找到解决办法了吗?

标签: laravel-5 phpunit


【解决方案1】:

在调用 api 之前尝试使用工厂创建一些数据:

例如:

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

然后

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

如果你在 phpunit.xml 中设置了“:memory:”作为你的数据库,你将不再看到本地数据库中的任何数据,这就是你应该使用工厂的原因。

【讨论】:

    猜你喜欢
    • 2012-01-01
    • 2018-11-04
    • 1970-01-01
    • 2018-05-03
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-30
    相关资源
    最近更新 更多