drzfnr0275 2018-05-09 21:50
浏览 95
已采纳

如何在Laravel中运行功能测试时模拟服务(或ServiceProvider)?

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 understanding the "Laravel way" to do what I want.

I am writing an HTTP API to, amongst other things, list, create and delete system users on a Linux server. The structure is like so:

  • Routes to /v1/users connect GET, POST and DELETE verbs to controller methods get, create and delete respectively.
  • The controller App\Http\Controllers\UserController does not actually run system calls, that is done by a service App\Services\Users.
  • The service is created by a ServiceProvider App\Providers\Server\Users that registers a singleton of the service on a deferred basis.
  • The service is instantiated by Laravel automatically and auto-injected into the controller's constructor.

OK, so this all works. I have also written some test code, like so:

public function testGetUsers()
{
    $response = $this->json('GET', '/v1/users');
    /* @var $response \Illuminate\Http\JsonResponse */

    $response
        ->assertStatus(200)
        ->assertJson(['ok' => true, ]);
}

This also works fine. However, this uses the normal bindings for the UserService, and I want to put a dummy/mock in here instead.

I think I need to change my UserService to an interface, which is easy, but I am not sure how to tell the underlying test system that I want it to run my controller, but with a non-standard service. I see App::bind() cropping up in Stack Overflow answers when researching this, but App is not automatically in scope in artisan-generated tests, so it feels like clutching at straws.

How can I instantiate a dummy service and then send it to Laravel when testing, so it does not use the standard ServiceProvider instead?

  • 写回答

2条回答 默认 最新

  • doulu8415 2018-05-09 22:41
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题