首次运行 phpunit 报错 Expected status code 201 but received 500 的解决方案。
10.2. Laravel API 集成测试之测试发布话题,修改完tests/Feature/TopicApiTest.php后首次$phpunit运行报错:
There was 1 failure:
1) Tests\Feature\TopicApiTest::testStoreTopic
Expected status code 201 but received 500.
Failed asserting that false is true.
/home/vagrant/Code/larabbs/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:185
/home/vagrant/Code/larabbs/tests/Feature/TopicApiTest.php:40
FAILURES!
Tests: 2, Assertions: 2, Failures: 1.
发生错误时,寻找错误原因的文件:
C:\Users\Administrator\Code\larabbs\storage\logs\laravel.log
因为 9.3. 本地化之添加测试代码章节,教程修改了store():
比如我们在 发布话题 接口的代码中增加下面的测试代码:
app/Http/Controllers/Api/TopicsController.php
...
public function store(TopicRequest $request, Topic $topic)
{
return $this->errorResponse(403, '您还没有通过认证', 1003);
...
而6.2. 发布话题之4. 增加 Controller原来store()如下:
public function store(TopicRequest $request, Topic $topic)
{
$topic->fill($request->all());
$topic->user_id = $request->user()->id;
$topic->save();
return new TopicResource($topic);
}
初学者很容易将store()改错,误删除return那一行以上的几行代码。建议 9.3. 本地化之添加测试代码章节,教程修改了store():在return之前增加…,修改如下,不会引起歧义:
public function store(TopicRequest $request, Topic $topic)
{ .
.
.
return $this->errorResponse(403, '您还没有通过认证', 1003);
将store函数修成6.2章节原样之后,再次运行$phpunit(用不到\larabbs\tests\Feature\ExampleTest.php,我把内容注释掉了)
vagrant@homestead:~/Code/larabbs$ phpunit
PHP Warning: Unterminated comment starting line 16 in /home/vagrant/Code/larabbs/tests/Feature/ExampleTest.php on line 16
Warning: Unterminated comment starting line 16 in /home/vagrant/Code/larabbs/tests/Feature/ExampleTest.php on line 16
<!-- PHPUnit 8.5.8 by Sebastian Bergmann and contributors.
.. 2 / 2 (100%)
Time: 22.05 seconds, Memory: 34.50 MB
OK (2 tests, 6 assertions)
推荐文章: