【问题标题】:Cannot pass $_GET to unit test无法将 $_GET 传递给单元测试
【发布时间】:2019-06-29 10:07:58
【问题描述】:

我无法将 $_GET['month'] 和 $_GET['day'] 传递给我的单元测试

$url = "https://api.abalin.net/get/namedays?day=5&month=2";
$response = $this
    ->json('GET', $url);

//这个也试过了

$var = ['month' => '2', 'day' => '5'];
$url = "https://api.abalin.net/get/namedays?day=5&month=2";

$response = $this
    ->json('GET', $url, $var);

在这种情况下执行后两者都会失败

if (!isset($_GET['month']) || !isset($_GET['day'])){
//
}

【问题讨论】:

  • 如果你使用 laravel,你应该使用 request 对象。
  • 你能分享一些简单的例子吗?
  • if (!request()->input('month') || !request()->input('day'))

标签: php laravel phpunit


【解决方案1】:

如果你使用的是 laravel,那么 $_GET 不是一个理想的测试方式。此外,laravel 的测试设置非常好,可以避免自己动手。

documentation 包含您需要的示例。

此外,单元测试是关于测试预期的输出,或者在某些情况下可能是测试数据转换直到输出的过程。

在您的情况下,如果您的测试本身通过 GET 方法中的 url 参数,那么测试它是否包含旁边的这些参数,并没有真正的帮助。相反,您应该为您期望的响应断言测试。

这是一个非常简单的例子:

<?php 

$response = $this->json('GET',  '/url',['month' => '2', 'day' => '5']);

// Check if response is successful with status code 200
$response->assertStatus(200);

// Check if response contains an expected data, for example `status` as `success`
$response->assertJson(['status' => 'success'];

如果您使用 laracast,this 将帮助您入门。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 2019-06-30
    • 2017-01-09
    • 2016-11-29
    相关资源
    最近更新 更多