2017-12-11 54 views
0

私は模擬しようとしています(例だけです)$ user-> posts() - > get()。phpUnit - 関係を使ってlaravelモデルを模倣する

例サービス:

use App\Models\User; 

class SomeClass{ 
    public function getActivePost(User $user): Collection 
    { 
     return $user->posts()->get(); 
    } 
} 

と私のモデル: とモデル:

namespace App\Models; 

use Illuminate\Database\Eloquent\Model; 
use Illuminate\Database\Eloquent\Relations\HasMany; 
use \App\Models\Post; 

class User extends Model 
{ 
    public function posts() : HasMany 
    { 
     return $this->hasMany(Post::class); 
    } 
} 

が、これは動作しません。

$this->user = Mockery::mock(User::class); 
$this->user 
    ->shouldReceive('wallets->get') 
    ->andReturn('test output'); 

エラー: はTypeError:の戻り値Mockery_2_App_Models_User :: posts()はIlluminate \ Databのインスタンスでなければなりませんase \ Eloquent \ Relations \ HasMany、Mockery_4__demeter_postsのインスタンスが返されました

戻りタイプのヒントなし(on post()メソッドなし)はすべて問題ありません。 andReturn()を変更する必要がありますか? idk how

+0

エラーが対応していないようだということあなたのコード内に何かがある。 – Devon

答えて

0

また、私はここでモックを使用しません。それは絶対に必要ありません。したがって、私が書いたユニットテストは次のようになります:

  • ユーザを作成します。
  • ユーザーが作成した投稿をいくつか作成します。
  • ユーザー&投稿にアサーションを実行します。

ので、コードは私のテストでは、このようなものになります:あなたはあなたができる関係をテストする場合

$user = factory(User::class)->create(); 
$posts = factory(Post::class, 5)->create(['user_id' => $user->id]); 

$this->assertNotEmpty($user->id); 
$this->assertNotEmpty($posts); 

$this->assertEquals(5, $posts->fresh()->count()); 
$this->assertEquals($user->id, $post->fresh()->first()->user_id); 
0

/** @test */ 
function user_has_many_posts() 
{ 
    $user = factory(User::class)->create(); 
    $post= factory(Post::class)->create(['user_id' => $user->id]); 

    //Check if database has the post.. 
    $this->assertDatabaseHas('posts', [ 
     'id' => $post->id, 
     'user_id' => $user->id, 
    ]); 
    //Check if relationship returns collection.. 
    $this->assertInstanceOf('\Illuminate\Database\Eloquent\Collection', $user->posts); 

}