如何测试调用 API 的方法? (Laravel)

How to test a method who calls an API? (Laravel)

我正在测试一种存储信用卡信息的方法,在该方法中我必须调用 API 请求银行存储所有卡信息然后他们 return 我用于进行未来交易的代币。

问题是当我测试方法时出现此错误

cURL error 60: SSL certificate problem: self signed certificate in certificate chain

这是我的测试方法

/**
 ** @test
 **/
public function a_logged_user_can_add_a_credit_debit_card()
{
  $demoCard = [
        'card_number' => '5424180279791732',
        'month' => '05',
        'year' => '2021',
        'cvc' => '123',
    ];

    $reponse = $this->postJson(route('card.create'),
        $demoCard, $this->user->headersToken());

    $reponse->assertJson(['success' => true]);

    $this->assertEquals(1, Tarjeta::first()->user_id);
    $this->assertEquals($this->tarjetaDemo['month'], Tarjeta::first()->month);
    $this->assertEquals($this->tarjetaDemo['year'], Tarjeta::first()->year);
    $this->assertEquals($this->tarjetaDemo['cvc'], Tarjeta::first()->cvc);
    $this->assertTrue(!empty(Tarjeta::first()->token));
}

这是我的方法

 private $clientEcomm;
/**
 * constructor.
 */
public function __construct()
{
    $merchant = env('MERCHANT_ECOMM');
    $apiPassword = env('API_ECOMM_PASSWORD');
    $apiUsername = env('API_ECOMM_USER');

    $this->clientEcomm = new Client([
        'base_uri' => "https://banamex.dialectpayments.com/api/rest/version/54/merchant/{$merchant}/",
        'auth' => [$apiUsername, $apiPassword]
    ]);
}

public function create(CardRequest $request)
{

    $response = $this->clientEcomm->put(
        "token",
        [
            'json' => [
                'sourceOfFunds' => [
                    'provided' => [
                        'card' => [
                            'number' => $request->get('card_number'),
                            'expiry' => [
                                'month' => $request->get('month'),
                                'year' => Str::substr($request->get('year'), -2),
                            ],
                            'securityCode' => $request->get('cvc')
                        ]
                    ],
                    'type' => 'CARD',
                ],
            ]
        ]
    );

    $response = \GuzzleHttp\json_decode($response->getBody()->getContents());

    Tarjeta::create([
        'user_id' => \Auth::user()->id,
        'mes' => $request->get('month'),
        'year' => $request->get('year'),
        'cvc' => $request->get('cvc'),
        'token' =>  $response->token,
    ]);

    return $this->successResponse();
}

如何进行此类测试?

为端点编写测试时,需要小心模拟对第三方的请求API。因此,在这种情况下,您需要模拟客户端。

public function __construct(Client $client)
{

}
$this->app->instance(Client::class, Mockery::mock(Client::class, function($mockery){
    $mockery->shouldReceive('put')->once()->with($parameters)->andReturn($response);
}));

这样,您的代码将永远不会调用第三方端点。