Question

I have an artisan command that I would like to write some unit tests for. However, I am using a model in it that has side effects, which will need to be mocked/stubbed. I tried using the standard laravel dependency injection method of adding an object of that class as an argument to the constructor, but it didn't work. How do I mock/stub/fake an object for testing purposes in an artisan command class?

No correct solution

OTHER TIPS

While artisan apparently does not support dependency injection, you can arranging things to allow it. In the class you are testing, instead of generating an object by calling it directly, use App::make instead. Then you can use App::bind to substitute another class for it.

So, in your target class, you would have:

$obj = App::make('Some_Class');

Then in your unit test function, you would do:

App::bind('Some_Class', 'SomeClassStub');

So that when your target class tries to create a Some_Class object, it will instead get an object of SomeClassStub.

Note that it might not automatically find the class you are substituting - you may need a require statement before it can be used, if the stub class file is not in the standard autoloaded locations. For example, I put my stub class in the same folder as my unit tests, which are not autoloaded by laravel. To add the directory to the autoloader, I put this in the unit test constructor:

Illuminate\Support\ClassLoader::addDirectories(__DIR__);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top