使用PHPunit命令测试我的应用程序时出现上述错误.
public function testProductCreationFailsWhenNameNotProvided() { $product = factory(\App\Product::class)->make(['name' => '']); $this->post(route('api.products.store'),$product->jsonSerialize()) ->seeJson(['name' => ['The name field is required.']]) /*line 86*/ ->assertResponseStatus(422); }
完整的错误报告在这里:
There was 1 error: 1) ExampleTest::testProductCreationFailsWhenNameNotProvided ErrorException: Invalid argument supplied for foreach() C:\xampp\htdocs\product- service\vendor\laravel\framework\src\Illuminate\Support\Arr.PHP:494 C:\xampp\htdocs\product-service\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\MakesHttpRequests.PHP:231 C:\xampp\htdocs\product-service\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\MakesHttpRequests.PHP:257 C:\xampp\htdocs\product-service\tests\ExampleTest.PHP:86 C:\xampp\PHP\pear\PHPUnit\TextUI\Command.PHP:176 C:\xampp\PHP\pear\PHPUnit\TextUI\Command.PHP:129 FAILURES! Tests: 7,Assertions: 43,Errors: 1.
我承认这段代码原本不是我的 – 它是从Laravel教程复制的.它在那里工作得很好.@H_502_20@不幸的是,这个相关问题的答案也没有帮助我.@H_502_20@Laravel 5.1 + PHPunit – API test returns always invalid argument error foreach
我试图修改它以传递json数组作为参数
public function testProductCreationFailsWhenNameNotProvided() { $product = factory(\App\Product::class)->make(['name' => '']); $this->post(route('api.products.store'),$product->jsonSerialize()) ->seeJson(json_encode(array('name' => ['The name field is required.']))) ->assertResponseStatus(422); }
但后来我收到了这个错误:
1) ExampleTest::testProductCreationFailsWhenNameNotProvided TypeError: Argument 1 passed to Illuminate\Foundation\Testing\TestCase::seeJson() must be of the type array,string given,called in C:\xampp\htdocs\product-service\tests\ExampleTest.PHP on line 86
解决方法
1) ExampleTest::testProductCreationFailsWhenNameNotProvided@H_502_20@ TypeError: Argument 1 passed to Illuminate\Foundation\Testing\TestCase::seeJson() must be of the type array,called in C:\xampp\htdocs\product-service\tests\ExampleTest.PHP on line 86
->seeJson(json_encode(array('name' => ['The name field is required.'])))
你必须改变它看起来像这样,它应该工作.
->seeJson(array('name' => ['The name field is required.']))