mardi 28 juin 2016

Unit testing a custom command

I've been able to test the behaviour of a custom command that I added.

However, I would like to be able to unit test it. All the logic that I have is in the handle method. I am injecting a class into the constructor of my custom command class. Now I would like to be able to mock it and use several scenarios with the mock.

Here is an example that illustrates How the custom class looks like:

class CustomCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'custom:generate 
                            {--myoption= : The option to generate }';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generates ...';

    /**
     * SqlMigrator class
     *
     * @customGenerator App\Scripts\CustomGenerator
     */
    private $customGenerator;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(CustomGenerator $cg)
    {
        parent::__construct();
        $this->customGenerator = $cg;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $myoption = $this->option('myoption');
        switch($myoption){
            case "case1": 
                            $this->cg->processCase1();
                            .
                            .
                            break;
            case "case2": 
                            .
                            .
                            .
                            break;
        }

Basically by mocking CustomGenerator class , and also setting the options of the custom class (myoption in this example) I will be able to unit test all the senarios.

All suggestions are welcome.

Thanks

Aucun commentaire:

Enregistrer un commentaire