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

12,598

Solution 1

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

Solution 2

Aha, I have found a temporary solution. I'll post it here, and then explain how it can be improved.

<?php

namespace Tests\Feature;

use Tests\TestCase;
use \App\Services\Users as UsersService;

class UsersTest extends TestCase
{
    /**
     * Checks the listing of users
     *
     * @return void
     */
    public function testGetUsers()
    {
        $this->app->bind(UsersService::class, function() {
            return new UsersDummy();
        });

        $response = $this->json('GET', '/v1/users');

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

class UsersDummy extends UsersService
{
    public function listUsers()
    {
        return ['tom', 'dick', 'harry', ];
    }
}

This injects a DI binding so that the default ServiceProvider does not need to kick in. If I add some debug code to $response like so:

/* @var $response \Illuminate\Http\JsonResponse */
print_r($response->getData(true));

then I get this output:

Array
(
    [ok] => 1
    [users] => Array
        (
            [0] => tom
            [1] => dick
            [2] => harry
        )

)

This has allowed me to create a test with a boundary drawn around the PHP, and no calls are made to the test box to interact with the user system.

I will next investigate whether my controller's constructor can be changed from a concrete implementation hint (\App\Services\Users) to an interface, so that my test implementation does not need to extend from the real one.

Share:
12,598
halfer
Author by

halfer

I'm a (mainly PHP) contract software engineer, with interests in containerisation, testing, automation and culture change. At the time of writing I am on a sabbatical to learn some new things - currently on the radar are Modern JavaScript, Jest and Kubernetes. I wrote a pretty good PHP tutorial, feedback on that is always welcome. I often scribble down software ideas on my blog. My avatar features a sleepy fur bundle that looks after me. I've written about how to ask questions on StackOverflow. I don't spend as much time answering questions these days - I think my time is better spent guiding people how to ask. I try to look after beginners on the platform - if anyone reading this has had a "baptism of fire", don't worry about it - it gets easier. If you'd like to get in touch, find the 'About' page of my blog: there's an email address there.

Updated on June 05, 2022

Comments

  • halfer
    halfer almost 2 years

    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?

  • halfer
    halfer about 6 years
    Ha ha, very similar to mine, posted just now! Thank you for this. I got mine through a mixture of auto-complete and guessing, rather than hard-won experience :-). I'll take a look at moving my binding to setUp() rather than doing it in each test though - good idea.
  • Kyslik
    Kyslik about 6 years
    @halfer Yea I see, good job! PHPStorm rocks :). Do that, create UserTestCase as I suggest and include the setUp() there. Problem with this is that when you need more than one re-binding you will end up mixing stuff up, so I'd suggest the conditional registering providers.
  • halfer
    halfer about 6 years
    I'll have a look at that, thanks. I'm intrigued by the function app() - is that a global, and is that different in some way to using $this->app? Naked functions feel a bit odd to me in classes, but I wonder if this is a Laravel thing that I just need to adjust to.
  • Kyslik
    Kyslik about 6 years
    @halfer Yea its a Laravel thing, there is plenty helpers that actually help :) see this file. For example I do not use app()->make(A::class) but resolve(A::class) which is app(A::class), or sometimes when I do not inject Request I simply use request() (if user is logged in I can access the instance via request()->user()), or abort(...), or route('route.name.here')... I sometimes make my own helper.php file and autoload it the same way how Laravel does it.
  • halfer
    halfer about 6 years
    Interesting. I like how the func definitions check to see if they exist already, so if they have been overridden, the custom implementation will be preferred. Alright, this has got me moving again - I appreciate your help.
  • Kyslik
    Kyslik about 6 years
    @halfer If you are really new to Laravel pick up some free courses on laracasts.com - Whats new in Laravel are really good ones or Laravel From Scratch - I am not sure what is free / paid. Good Luck.