首页 > 解决方案 > App\Billing\FakePaymentGateway 类的对象无法转换为字符串

问题描述

有 1 个错误:

1) ViewConcertListingTest::customer_can_purchase_concert_tickets ErrorException: 类 App\Billing\FakePaymentGateway 的对象无法转换为字符串

正在做测试,但无法弄清楚它在抱怨什么......

<?php

namespace App\Billing;

class FakePaymentGateway implements PaymentGateway
{

    private $charges;

    public function __construct()
    {
        $this->charges = collect();
    }


    public function getValidTestToken()
    {
        return "valid-token";
    }



    public function charge($amount, $token)
    {
        $this->charges[] = $amount;
    }

    public function totalCharges()
    {
        return $this->charges->sum();
    }

}

这是它的另一部分 PurchaseTiketTest.php

<?php
    class ViewConcertListingTest extends TestCase
    {
    use DatabaseMigrations;
    /**
    * @test
    *
    * @return void
    */
    public function customer_can_purchase_concert_tickets()
    {
    $paymentGateway = new FakePaymentGateway;

    $this->app->instance(PaymentGateway::class, $paymentGateway);
    //dd($paymentGateway);

    // Arrange

    //Create a concert
    $concert = factory(Concert::class)->create(['ticket_price' => 3250 ]);


    // Act

    // View the concert listing

    $response = $this->json('POST', "/concerts/{$concert->id}/orders", [
    'email' => 'john@example.com',
    'ticket_quantity' => 3,
    'payment_token' => $paymentGateway->getValidTestToken(),
    ] );

    $response->assertStatus(201);


    $this->assertEquals( 9750 , $paymentGateway->totalCharges() );

    $order = $concert->orders()->where('email')->first();

    $this->$this->assertNotNull($order);

    $this->assertEquals( 3, $order->tickets->count() );
    }


    }

在第 18 行添加注释的订单控制器

class ConcertsOrdersController extends Controller
{

    private $paymentGateway;

    public function __construct(PaymentGateway $paymentGateway)
    {
        $this->$paymentGateway = $paymentGateway; // Line 18
    }

    //
    public function store($concertId)
    {
        $concert = Concert::find($concertId);

        $ticketQuantity = request('ticket_quantity');

        $amount = $ticketQuantity * $concert->ticket_price;

        $token = request('payment_token');

        $this->paymentGateway->charge($amount, $token);


$concert->orders()->create(['email' => request('email')]);


        return response()->json([], 201);
    }
}

预计通过结果

标签: phplaravelobjectpayment-gateway

解决方案


$您的错误是第 18 行的属性名称之前的一个简单附加(不需要)ConcertsOrdersController

    $this->$paymentGateway = $paymentGateway; // Line 18

当你这样做时,你告诉 PHP 获取$paymentGateway字符串的值,并设置一个使用该字符串值调用的方法。

例如:

$paymentGateway = 'test';
$this->$paymentGateway = 123;
echo $this->$paymentGateway; // 123
echo $this->test; // 123

发生错误是因为您的$paymentGateway变量是对象而不是字符串。

实际上,您在第 18 行添加了一个额外$的内容。它应该如下所示:

    $this->paymentGateway = $paymentGateway; // Line 18

推荐阅读