【问题标题】:How to create a payment method for testing in Laravel Cashier with phpunit and stripe如何使用 phpunit 和 stripe 在 Laravel Cashier 中创建用于测试的支付方式
【发布时间】:2022-11-18 07:25:29
【问题描述】:

我有一个问题,我希望你能帮助我,在浏览器中,我的应用程序运行良好,但如果我尝试在 phpunit 中测试它,它没有通过测试。

正如 laravel 文档所说,我正在使用真正的 stripe api: https://laravel.com/docs/8.x/billing#testing

但我在测试模式下使用它,在浏览器中我只使用测试信用卡号:4242424242424242,如这里所述:https://stripe.com/docs/testing

在我的控制器中我有这个:

....
DB::beginTransaction();            
           
$user = User::firstOrCreate([                    
        'email' => $request->user_email
 ],
 [                                     
 'name' => $request->user_name,   
 'password' => Hash::make($request->user_password)
]        
 );            

$user->createOrGetStripeCustomer();
....
....
$user->charge($amount, $request->payment_method_id);

Mail::send(new ProjectCreated($project));
....
....

项目测试.php

...
use Illuminate\Support\Facades\Mail;
use App\Mail\ProjectCreated;

class ProjectTest extends TestCase
{
    use RefreshDatabase;

    public function test_an_email_is_sent_when_a_project_is_submitted()
    {                
        //given        
        Mail::fake();        

        // when
        $project = Project::factory()->make();          

        $response = $this->post(route('projects.store'), $project->toArray()+['payment_method_id' => 'test']);            

        //then
        $response->assertOk();
    }
}

phpunit.xml

<server name="APP_ENV" value="testing"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<server name="DB_CONNECTION" value="sqlite"/>
<server name="DB_DATABASE" value=":memory:"/>
<server name="MAIL_MAILER" value="log"/>
<server name="STRIPE_SECRET" value="sk_test_xxxxxxxxxxxxxxxxxxxxxxx"/>                
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="array"/>
<server name="TELESCOPE_ENABLED" value="false"/> 

Phpunit 消息:

没有这样的付款方式:“测试”

我如何创建用于测试的付款方式?还是最好不要点击 stripe api?你如何在你的项目中做到这一点?谢谢。

【问题讨论】:

  • 没有任何使用 Laravel Cashier 或 phpunit 的经验,但如果您只需要创建一个测试支付方式,那么通过 Stripe APIdashboard 可以很容易地完成。

标签: php laravel phpunit stripe-payments


【解决方案1】:

我只需要添加以下任何一种付款方式:pm_card_visa,pm_card_visa_debit等,这里是完整列表:https://stripe.com/docs/testing?testing-method=payment-methods

public function test_an_email_is_sent_when_a_project_is_submitted()
    {                
        //given        
        Mail::fake();        

        // when
        $project = Project::factory()->make();          

        $response = $this->post(route('projects.store'), 
        $project->toArray()+['payment_method_id' => 'pm_card_visa']);            

        //then
        $response->assertOk();
    }

谢谢你。

【讨论】:

    猜你喜欢
    • 2020-11-23
    • 2020-06-09
    • 2021-01-31
    • 2015-10-27
    • 2020-05-09
    • 2023-02-06
    • 2018-10-21
    • 2015-12-19
    • 2019-03-18
    相关资源
    最近更新 更多