测试 Eloquent Model
打赏作者

uighurbabbage

老师用的phpstrom主题是那个主题 感觉很干净

wx630370

站长,调用create()方法时,报Error: Call to a member function make() on null ?

Ericxie

jelly老师,我运行test的时候出现以下问题

There was 1 error:

1) Tests\Unit\ArticleTest::itFetchesTrendingArticles
InvalidArgumentException: Unable to locate factory with name [default] [App\Article].

奇怪的是,我在tinker里面运行factory方法却一点问题都没有,我试过清除缓存和composer dump-autoload也没有效果,请问老师问题是出现在哪里呢?@jellybool
我的factory方法

$factory->define(App\Article::class, function (Faker $faker) {
    return [
        'title' => $faker->sentence,
    ];
});

我的testcase

class ArticleTest extends TestCase {
    /** @test */
    public function itFetchesTrendingArticles(){
        factory(Article::class,3)->create();
        factory(Article::class)->create(['read' => 10]);
        $mostPopular = factory(Article::class)->create(['read' => 20]);

        $articles = Article::trending();

        $this->assertEquals($mostPopular->id, $articles->first()->id);
    }
}

我的article model

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    public function scopeTrending($query){

    }
}
JellyBool 回复 Ericxie
App\Article::class 改成 \App\Article::class 这样试试
Ericxie 回复 JellyBool

还是不行,我创建一个新项目又可以了。。。

JellyBool 回复 Ericxie

有这么奇怪的么?。。。

zxhs1988 回复 JellyBool

我也遇到这样的问题了

xiabo 回复 JellyBool

就是这么奇怪!我用的5.5也出现了这个问题!

haohexin

$mostPopular = factory(Article::class, 1)->create([‘reads’ => 20]);
laravel5.5 返回的是 all collection格式
断言时
this>assertEquals(this->assertEquals(mostPopular->first()->id, $articles->first()->id);