我正在通过Laracast教程:link。我的论坛项目在浏览器中工作。我可以看到所有线程都有相关的回复。这些回复包含带时间戳的用户信息。但是phpunit测试失败了,我无法理解为什么:
λ vendor\bin\phpunit tests\Unit\ReplyTest.php
PHPUnit 5.7.21 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
Time: 360 ms, Memory: 12.00MB
There was 1 failure:
1) Tests\Unit\ReplyTest::it_has_an_owner
Failed asserting that null is an instance of class "App\User".
C:\laragon\www\forum\tests\Unit\ReplyTest.php:19
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
这是我的 ReplyTest.php :
<?php
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class ReplyTest extends TestCase
{
use DatabaseMigrations;
/** @test **/
public function it_has_an_owner()
{
$reply = factory('App\User')->create();
$this->assertInstanceOf('App\User', $reply->owner);
}
}
我的雄辩模型 Reply.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Reply extends Model
{
public function owner()
{
return $this->belongsTo(User::class, 'user_id');
}
}
来自 ModelFactory.php的代码:
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
static $password;
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => str_random(10),
];
});
$factory->define(App\Thread::class, function (Faker\Generator $faker) {
static $password;
return [
'user_id' => function() {
return factory('App\User')->create()->id;
},
'title' => $faker->sentence,
'body' => $faker->paragraph
];
});
$factory->define(App\Reply::class, function (Faker\Generator $faker) {
static $password;
return [
'thread_id' => function() {
return factory('App\Thread')->create()->id;
},
'user_id' => function() {
return factory('App\User')->create()->id;
},
'body' => $faker->paragraph
];
});
show.blade.php
的代码摘录<div class="col-md-8 col-md-offset-2">
@foreach ($thread->replies as $reply)
<div class="panel-heading">
<a href="#">
{{ $reply->owner->name }}
</a>
said {{ $reply->created_at->diffForHumans() }} ...
</div>
<div class="panel panel-default">
<div class="panel-body">
{{ $reply->body }}
</div>
</div>
@endforeach
</div>
我希望我发布所有相关代码 - 如果没有,请告诉我你需要什么,我会发布它。我无法弄清楚为什么phpunit会在浏览器中一切正常时返回错误。
答案 0 :(得分:0)
最终发现了我的错误。我使用工厂的错误类和创建用户而不是回复。更改后一切正常:
$reply = factory('App\Reply')->create();