3

I am using Laravel 5.3. For a procedur I am using a command. The command class is calling a method of an another class. I wanted to unit test it with phpunit. Therefore I mocked up the class within the command class. When I run the test, then the actual method of class is running and not the mocked method. Bevor I have implemented the functinality of the command in a job. There I can call the mocked method without any problem.

The test class looks like this:

class CommandTest extends TestCase
{
    public function setUp()
    {
         parent::setUp();
         $this->api = $this->getMockBuilder('App\Services\APIRepository')
         ->setMethods(['getStatus'])
         ->getMock();
    }

    /** @test */
    public function test_api()
    {
         ...
         $this->api->expects($this->any())
             ->method('getStatus')
             ->will($this->returnValue($api_response));
         \Artisan::call('myapp:tracker',[]);
         ...
    }
}

class Command extends Command
{
    protected $signature = 'myapp:tracker';
    private $api;

    public function __construct(APIRepository $api)
    {
         $this->api = $api;
    }

    public function handle()
    {
         ...
         $status = $this->api->getStatus(...);
         var_dump($status);
         ...
    }
}

The output of var_dump($status) is: NULL

Do I need a special method for mocking a class within a command class?

Thanks a lot in advanced!

toye
  • 65
  • 4
  • What you've written looks fine (aside from the duplicated function name, which I assume is a mistake in your question rather than your original code) so you'll need to provide more code I think. It's hard to know what could be going wrong at the moment - for example: how do you actually call `$this->api`? You don't share that code – scrowler Apr 24 '18 at 04:03
  • @Robbie As you aspected it was a mistage in my question. I fixed the duplicated function name and provided the command class with the call of `$this->api` – toye Apr 24 '18 at 12:09

0 Answers0