jokersk / sonata
用于Laravel测试
0.04
2021-06-25 03:32 UTC
README
使Laravel测试更简单
安装
composer require jokersk/sonata
在你的测试文件中添加Sonata\Traits\LetsPlaySonata特性,就这样!
使用
use Sonata\Traits\LetsPlaySonata; class SomeTest extends TestCase { use LetsPlaySonata, RefreshDatabase; ... }
假设你有一个模型\App\Models\Post,我们可以创建这样的模型
$this->create(Post::class);
如果你想要获取创建的帖子模型,你可以
$post = $this->create(Post::class)->getCreated();
创建带有关系的模型
现在我们有一个模型\App\Models\Comment,在\App\Models\Post模型中有HasMany关系,例如
public function comments() { return $this->hasMany(Comment::class); }
我们可以不使用sonata创建这样的模型
$post = Post::factory()->create(); $comment = Comment::factory()->create(['post_id' => $post->id]);
但是使用sonata,你可以创建这样的模型
$this->create(Post::class)->with(Comment::class);
无论是HasMany, BelongsTo, BelongsToMany, morphMany, morphToMany,你都可以使用with函数,sonata会为你处理save, associate, or attach
如果你想要获取创建的模型,你可以
[$post, $comment] = $this->create(Post::class)->with(Comment::class)->get([Post::class, Comment::class]);
或者
[$post, $comment] = $this->create(Post::class)->with(Comment::class)->get();
使用属性创建
$this->create(Post::class, [ 'title' => 'abc', 'body' => 'hi' ]);
或者
$this->set([ 'title' => 'abc', 'body' => 'hi' ])->create(Post::class);
要设置属性给with函数,我们可以这样做
$this->create(Post::class)->with(Comment::class, [ 'body' => 'foo' ]);
覆盖函数名
默认情况下,Sonata会查找正确的函数名,但有时你的函数名是不可预测的,例如Post模型有多个Comment,所以你会调用comments函数,但有时会调用activeComments函数,在这种情况下,你可以调用
$this->create(Post::class)->by('activeComments')->with(Comment::class);
从现有模型创建关系
可以使用createFrom方法来与现有模型创建关系
$post = Post::factory()->create(); $comment = $this->createFrom($post)->with(Comment::class)->get(Comment::class);
模拟
$foo = Sonata::createMock('where()->first()->content', 'hello');
现在你调用$foo->where()->first()->content,将等于'hello'