Laravel/Testing

Mocking

Sein_ 2023. 9. 19. 18:37
728x90

Mock: 모조품

 

Mocking 이란?

테스팅 진행시 이벤트가 실제 일어나지 않게 가짜로 실행하여 컨트롤러의 HTTP response 응답만 테스트할 수 있도록 하는 기능

 

//Searcer.php (controller)
$response = $this->client->request('get', $this->url . $this->subUrl, [
    RequestOptions::HEADERS => [
        'X-ServiceId' => $this->serviceId,
        'X-AccessKey' => $this->accessKey,
        'X-Fingerprint' => $this->getSignature($signatureUrl),
        'X-Fingerprint-Timestamp' => $this->timestamp,
    ],
    RequestOptions::QUERY => get_object_vars($request),
]);

 

 

//Base.php (Searcher 부모)
public function __construct(
    protected Client     $client,
    protected JsonMapper $jsonMapper,
)

 

 

//SearcherTest.php (controller test)
public function 주문_조회_테스트()
{
//Mocking
    $client = new Client([
        'handler' => new MockHandler([
            new Response(200, [], file_get_contents(__DIR__ . '/search-result.json')),
        ]),
    ]);

    $searcher = new Searcher(
        $client,
        new \JsonMapper()
    );

    $result = $searcher->search(new SearchRequest());
    $this->assertIsObject($result);

}

 

 

 

참고

https://docs.guzzlephp.org/en/stable/testing.html

 

Testing Guzzle Clients — Guzzle Documentation

Guzzle provides several tools that will enable you to easily mock the HTTP layer without needing to send requests over the internet. Mock Handler When testing HTTP clients, you often need to simulate specific scenarios like returning a successful response,

docs.guzzlephp.org