2016-07-11 10 views
0

例:Laravelでエンドポイントを呼び出す際に、コントローラに注入されたオブジェクトをモックする方法は?

私はエンドポイント/something/coolとルートファイルがあります。

$router->get('/something/cool', [ 
    'uses' => '[email protected]', 
]); 

を私はMyControllerという名前のコントローラを持っています。 MyControllerには、myFunctionOneという名前の関数があります。 myFunctionOneパラメータには、私は注入サービスクラスMyServiceがあります。 MyServiceには、外部API callExternalApi()を呼び出す関数があります。私は、機能テストを持っている反対側に

class MyController 
{ 
    public function myFunctionOne(MyService $myService) 
    { 
     $myService->callExternalApi(); 

     // do some other things.. 
    } 
} 

はここに私のコントローラがどのように見えるかだ

class SomethingCoolTest extends TestCase 
{ 
    public function testSomethingCool() 
    { 
     // callin my Route Endpoint (real http call to my app) 
     $this->get('/something/cool', [])->response; 

     // do some assertions.. 
    } 
} 

私の質問は:どのように私は、コントローラを注入サービスを模擬することができ、それは外部サービスを呼び出しているからですか?私は予想以上に簡単だった

答えて

0

:すると、次のように、お好きなサービスをモック

public function mock($class) 
{ 
    $mock = \Mockery::mock($class); 

    $this->app->instance($class, $mock); 

    return $mock; 
} 

:D

まずモックという名前のモックヘルパー関数を作成

$mimo = $this->mock(MyService::class); 

    $mimo->shouldReceive('callExternalApi')->once()->andReturn([ 
     "anything" => "cool" 
    ]); 
関連する問題