Skip to content
Advertisement

Laravel 5 console (artisan) command unit tests

I am migrating my Laravel 4.2 app to 5.1 (starting with 5.0) and am a lot of trouble with my console command unit tests. I have artisan commands for which I need to test the produced console output, proper question/response handling and interactions with other services (using mocks). For all its merits, the Laravel doc is unfortunately silent with regards to testing console commands.

I finally found a way to create those tests, but it feels like a hack with those setLaravel and setApplication calls.

Is there a better way to do this? I wish I could add my mock instances to the Laravel IoC container and let it create the commands to test with everything properly set. I’m afraid my unit tests will break easily with newer Laravel versions.

Here’s my unit test:

Use statements:

JavaScript

Setup

JavaScript

Input provided as command arguments. Checks console output

JavaScript

Input provided by simulated keyboard keys

JavaScript

updates

  1. This doesn’t work in Laravel 5.1 #11946

Advertisement

Answer

I have done this before as follows – my console command returns a json response:

JavaScript

So if you want to put this in it’s own command tester class, or as a function within TestCase etc… up to you.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement