【问题标题】:Laravel 5.1 + PHPunit - API test returns always invalid argument error foreachLaravel 5.1 + PHPunit - API 测试总是返回无效参数错误 foreach
【发布时间】:2015-11-02 11:30:08
【问题描述】:

我已经从 Laravel 5.0 升级到 5.1

测试套件工作正常,我可以运行 phpunit 命令。但是,当我开始使用 api 测试进行测试时,我总是得到一个 foreach 错误。

class ExampleTest extends TestCase {

    public function testLoginCredentials()
    {
        $this->post('/srv/plc/auth/login', ['data' => 'some data'])
        ->seeJson([
            'authorized' => true,
        ]);
    }
}

上面看起来像文档:http://laravel.com/docs/5.1/testing#testing-json-apis

如果我通过 phpunit 运行测试,我会收到以下错误:

There was 1 error:

1) ExampleTest::testBasicExample
ErrorException: Invalid argument supplied for foreach()
/Applications/XAMPP/xamppfiles/htdocs/w/server/vendor/framework/src/Illuminate/Support/Arr.php:423
/Applications/XAMPP/xamppfiles/htdocs/w/server/vendor/framework/src/Illuminate/Support/helpers.php:301
/Applications/XAMPP/xamppfiles/htdocs/w/server/vendor/framework/src/Illuminate/Foundation/Testing/CrawlerTrait.php:365
/Applications/XAMPP/xamppfiles/htdocs/whennn/server/vendor/laravel/framework/src/Illuminate/Foundation/Testing/CrawlerTrait.php:352
/Applications/XAMPP/xamppfiles/htdocs/whennn/server/tests/ExampleTest.php:17
/Applications/XAMPP/xamppfiles/lib/php/PHPUnit/TextUI/Command.php:188
/Applications/XAMPP/xamppfiles/lib/php/PHPUnit/TextUI/Command.php:126

FAILURES!
Tests: 1, Assertions: 0, Errors: 1.

如果我使用 $this->get 执行 get 请求,我会收到同样的错误。与其他端点相同的错误。

$this->访问正常。

【问题讨论】:

    标签: php api laravel phpunit tdd


    【解决方案1】:

    经过大量调试....

    • seeJson() 只接受 Json 数组(不是 Json 对象)
    • 当测试的端点不返回数组时,会出现 Foreach 错误。如果有多个数组,则会出现错误。

    真不知道为什么seeJson一定是数组。

    我预计会出现“断言错误”,而不是 foreach 错误

    【讨论】:

    • 这解决了我的问题,谢谢。我只是在尚未实现的 API 端点上返回 response('ok')。确实很奇怪,它没有给出断言错误...
    猜你喜欢
    • 2022-10-02
    • 2020-11-11
    • 2015-09-26
    • 2020-12-09
    • 2015-10-04
    • 1970-01-01
    • 2021-12-18
    • 2021-12-04
    • 2013-12-21
    相关资源
    最近更新 更多