Summer Sale! All accounts are 50% off this week.

drewdan's avatar
Level 15

Testing artisan command fails to resolve mocks

Hi Guys,

I have a Artisan test which mocks a class, when I run the command, Laravel does not resolve the mock from the service container.

public function testHandle() {
		$company = Company::whereName('durham-cc')->first();
		factory(Interaction::class, 10)->create(['company_id' => $company->id]);
		$mock = $this->mock(DataTransferClient::class)
			->shouldReceive('uploadFile')
			->withAnyArgs()
			->once();
		app()->offsetSet(DataTransferClient::class, $mock);
		$this->artisan('interaction:durham-transfer')
			->assertExitCode(0);
	}

The command gets called, and in the constructor:

public function __construct(DataTransferClient $client, InteractionLogService $interactionLogService) {
		$this->client = $client;
		$this->interactionLogService = $interactionLogService;
	}

I am resolving the DataTransferClient - but the real client gets resolved instead of the mock.

Any ideas?

0 likes
7 replies
bugsysha's avatar
bugsysha
Best Answer
Level 61

Commands resolve dependencies type hinted in the handle method, not in the constructor. Try that.

3 likes
drewdan's avatar
Level 15

I could kiss you right now! That was it, I have spent ages trying to figure this out, mocking in 10 different ways. Thank you so much :D

bugsysha's avatar

No need for kissing. Just remember that commands and jobs resolve dependencies from the handle method.

1 like
drewdan's avatar
Level 15

Noted, thing this is one I won't forget :D Thanks again :)

Please or to participate in this conversation.