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
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.
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