如何使用 phpunit 在 laravel 中模拟 paypal 交易?

Har*_*osh 5 phpunit laravel mockery omnipay

测试时:

从我的网站结帐商品时,需要模拟确认...以便我们可以继续处理订单。哪里可以进行测试..

我如何将好的代码换成模拟?例如:

$gateway = Omnipay::create('paypal');
$response = $gateway->purchase($request['params'])->send();
if ($response->isSuccessful()) { ... etc ...
Run Code Online (Sandbox Code Playgroud)

这怎么可能?

虽然我创建了测试,但我在模拟领域的知识是基础的

在此输入图像描述

tra*_*fox 4

就其取决于模拟而言,您不需要知道确切的响应,您只需要知道输入和输出数据,并且您应该在 laravel 服务提供商中替换您的服务(在本例中为 Paypal)。您需要执行如下步骤: 首先添加PaymentProvider到您的 laravel 服务提供商:

class AppServiceProvider extends ServiceProvider
{
   ...

   /**
    * Register any application services.
    *
    * @return void
    */
    public function register()
    {
        $this->app->bind(PaymentProviderInterface::class, function ($app) {
            $httpClient = $this->app()->make(Guzzle::class);
            return new PaypalPackageYourAreUsing($requiredDataForYourPackage, $httpClient);
        });
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

然后在您的测试类中,您应该用该接口的模拟版本替换您的提供程序:

class PaypalPackageTest extends TestCase
{
   /** @test */
   public function it_should_call_to_paypal_endpoint()
   {
       $requiredData = $this->faker->url;
       $httpClient = $this->createMock(Guzzle::class);
       $paypalClient = $this->getMockBuilder(PaymentProviderInterface::class)
           ->setConstructorArgs([$requiredData, $httpClient])
           ->setMethod(['call'])
           ->getMock();

       $this->instance(PaymentProviderInterface::class, $paypalClient);

       $paypalClient->expects($this->once())->method('call')->with($requiredData)
           ->willReturn($httpClient);

       $this->assertInstanceOf($httpClient, $paypalClient->pay());
   }
}
Run Code Online (Sandbox Code Playgroud)