php - 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);
}
}
预计通过结果
解决方案
$
您的错误是第 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
推荐阅读
- c# - C#如何在Task.WhenAll中捕获任务结果?“.Result”或“等待”
- python - 当有使用 Django 的可用选项时,如何使依赖下拉列表成为必需?
- macos - 在 Mac 上运行 Visual Studio Code 时出现问题
- c# - 大写 JSON 键
- android - 如何将 FirestoreDocumentReference 放入 CloudFirestore 中的类型映射字段
- django - Docker 应用服务器 ip 地址 127.0.0.1 差 0.0.0.0 ip
- reactjs - 反应 redux 容器将状态发送到另一个容器
- django - Django:在视图中访问 num_pages 以生成分页
- flutter - 如何使用具有动态长度的 StaggeredGridView?
- ios - 使用 AVPlayer 对象初始化 SKVideoNode - SWIFT