Laravel framework classes not available in PHPUnit data provider

前端 未结 3 997
忘掉有多难
忘掉有多难 2020-12-31 05:59

I have something like the following set up in Laravel:

In /app/controllers/MyController.php:

class MyController extends         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 06:19

    Performance warning for the other solutions (especially if you plan to use factories inside your dataProviders):

    As this article explains:

    The test runner builds a test suite by scanning all of your test directories […] When a @dataProvider annotation is found, the referenced data provider is EXECUTED, then a TestCase is created and added to the TestSuite for each dataset in the provider.

    […]

    if you use factory methods in your data providers, these factories will run once for each test utilizing this data provider BEFORE your first test even runs. So a data provider […] that is used by ten tests will run ten times before your first test even runs. This could drastically slow down the time until your first test executes. Even […] using phpunit --filter, every data provider will still run multiple times. Filtering occurs after the test suite has been generated and therefore after any data providers have been executed.

    The above article proposes to return a closure from the dataProvider and execute that in your test:

    /** 
     * @test
     * @dataProvider paymentProcessorProvider
     */
    public function user_can_charge_an_amount($paymentProcessorProvider)
    {
        $paymentProcessorProvider();
        $paymentProcessor = $this->app->make(PaymentProviderContract::class);
    
        $paymentProcessor->charge(2000);
    
        $this->assertEquals(2000, $paymentProcessor->totalCharges());
    }
    
    public function paymentProcessorProvider()
    {
        return [
            'Braintree processor' => [function () {
                $container = Container::getInstance();
                $container->bind(PaymentProviderContract::class, BraintreeProvider::class);
            }],
            ...
        ];
    }
    

提交回复
热议问题