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 为啥画版图在Run DRC会出现Connect Error?可我Calibre的hostname和计算机的hostname已经设置成一样的了。
  • ¥20 网站后台使用极速模式非常的卡
  • ¥20 Keil uVision5创建project没反应
  • ¥15 mmseqs内存报错
  • ¥15 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography
  • ¥100 求抖音ck号 或者提ck教程
  • ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)