public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->unsignedInteger('reads')->default(0);
$table->timestamps();
});
}
use App\Article;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
class ArticleTest extends TestCase
{
use DatabaseTransactions;//truncate table;
/**
A basic test example.
@return void
*/
/* @test /
public function it_fetchs_trending_articles()
{
factory(Article::class,3)->create();
$mostPopular = factory(Article::class)->create();
$articles = Article::trending();
$this->assertEquals($mostPopular->id,$articles->first()->id);
}
}
### Running phpunit
vendor/bin/phpunit --filter=ArticleTest
or
cp vendor/bin/phpunit ./
phpunit --filter=ArticleTest
会发现报错,因为Article里没有trending方法
### queryScope
>edit Article.php add the following content
public function scopeTrending($query){
return $query->orderBy('id', 'desc');
}
### Re Running phpunit
![phpuniy](https://user-images.githubusercontent.com/4393443/36946889-2c29e82c-1fff-11e8-9b2b-c6a6c0c8e255.png)
Eloquent Model
Create Model and Migrations
Edit Migrations
Using Model Factories
Create Test Database
<?php
namespace Tests\Feature;
use App\Article; use Illuminate\Foundation\Testing\DatabaseTransactions; use Tests\TestCase; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase;
class ArticleTest extends TestCase { use DatabaseTransactions;//truncate table; /**
@return void */
/* @test / public function it_fetchs_trending_articles() { factory(Article::class,3)->create(); $mostPopular = factory(Article::class)->create(); $articles = Article::trending(); $this->assertEquals($mostPopular->id,$articles->first()->id); } }
vendor/bin/phpunit --filter=ArticleTest or cp vendor/bin/phpunit ./ phpunit --filter=ArticleTest
public function scopeTrending($query){ return $query->orderBy('id', 'desc'); }
参考链接