How to mock a service (or a ServiceProvider) when running Feature tests in Laravel?

前端 未结 2 1398
天涯浪人
天涯浪人 2021-01-03 04:06

I\'m writing a small API in Laravel, partly for the purposes of learning this framework. I think I have spotted a gaping hole in the docs, but it may be due to my not unders

2条回答
  •  悲哀的现实
    2021-01-03 04:37

    The obvious way is to re-bind the implementation in setUp().

    Make your self a new UserTestCase (or edit the one provided by Laravel) and add:

    abstract class TestCase extends BaseTestCase
    {
        use CreatesApplication;
    
        protected function setUp()
        {
            parent::setUp();
    
            app()->bind(YourService::class, function() { // not a service provider but the target of service provider
                return new YourFakeService();
            });
        }
    }
    
    class YourFakeService {} // I personally keep fakes in the test files itself if they are short
    

    Register providers conditionally based on environment (put this in AppServiceProvider.php or any other provider that you designate for this task - ConditionalLoaderServiceProvider.php or whatever) in register() method

    if (app()->environment('testing')) {
        app()->register(FakeUserProvider::class);
    } else {
        app()->register(UserProvider::class);
    }
    

    Note: drawback is that list of providers is on two places one in config/app.php and one in the AppServiceProvider.php

提交回复
热议问题