mercredi 12 octobre 2016

In Laravel, how to give another implementation to the service container when testing?

I'm creating a Laravel controller where a Random string generator interface gets injected to one of the methods. Then in AppServiceProvider I'm registering an implementation. This works fine.

The controller uses the random string as input to save data to the database. Since it's random, I can't test it (using MakesHttpRequests) like so:

$this->post('/api/v1/do_things', ['email' => $this->email])
->seeInDatabase('things', ['email' => $this->email, 'random' => 'abc123']);

because I don't know what 'abc123' will be when using the actual random generator. So I created another implementation of the Random interface that always returns 'abc123' so I could assert against that.

Question is: how do I bind to this fake generator at testing time? I tried to do

$this->app->bind('Random', 'TestableRandom');

right before the test, but it still uses the actual generator that I register in AppServiceProvider. Any ideas? Am I on the wrong track completely regarding how to test such a thing?

Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire