Wednesday, March 1, 2017

Laravel mockery - mocking injected class in Artisan do not work

I am using Laravel 5.2. I have a ABCCommand like this:

class ABCCommand extends Command
{
    protected $signature = 'abc-cmd';
    private $classA;
    public function __construct(ClassA $classA)
    {
        parent::__construct();
        $this->classA = $classA;
    }
    public function handle()
    {
        $result = $this->classA->method1();
        $this->info($result);
    }
}

This is my ClassA:

ClassA {
    public function method1() {
         if($this->method2()) {
              return "Yes";
         }
         return "No";
    }
    public function method2() {
         return false;
    }
}

I would like to make partial like this:

class ABCCommandTest extends TestCase {
    public function __construct() {
         parent::_construct();
    }
    private function mock($class) {
         $mockClass = Mockery::mock($class);
         return $this->app->instance(preg_replace('/\[.*\]/', '', $class), $mockClass);  
    }
    public function testABCCommandOK() {
         $this->mock('ClassA[method2]')
               ->shouldReceive('method2')
               ->andReturn(true);
         $result = $this->artisan('abc-cmd')->output();
         $thisAssertEquals('Yes', $result);
    }
}

Hit phpunit. It's always failed. It seed mockery do not work.

Any Guru, please help. Many thanks!




via Bơ Loong A Nhứi

Advertisement