【发布时间】:2018-01-18 13:07:45
【问题描述】:
我正在学习 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);
}
}
我的 Eloquent 模型 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 在浏览器中一切正常时返回错误。
【问题讨论】:
-
请不要在标题后面附加 solved。而是考虑将答案标记为已接受。这将告诉其他人问题现已解决。谢谢。
-
@Bugs 我不能,因为我收到一条通知“您可以在 2 天内接受自己的答案”。你知道我为什么要等这么久吗?
-
围绕这个主题有一些元数据。这是链接; Why can't you accept your own answer immediately? 和 Why must I wait 2 days before accepting my own answer? 应该会给你你正在寻找的答案。这有点痛苦,但我想这些规则是为了阻止人们玩这个系统。
-
测试的目的是什么?
-
我们不需要视图,并且
static属性$password从未用于为App\Thread和App\Reply创建固定装置的闭包中。此外,您也可以在测试中使用class关键字。