2016-07-11 2 views
0

예 :Laravel에서 끝점을 호출하는 동안 Controller에 주입 된 객체를 조롱하는 방법?

나는 엔드 포인트 /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

: D

먼저 모의라는 조롱 도우미 함수 작성 :

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

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

    return $mock; 
} 

그런 다음 당신이 원하는 서비스를 모의, 다음과 같은 :

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

    $mimo->shouldReceive('callExternalApi')->once()->andReturn([ 
     "anything" => "cool" 
    ]); 
관련 문제