Skip to content

Instantly share code, notes, and snippets.

@gizzmo
Created June 15, 2017 02:51
Show Gist options
  • Save gizzmo/9f7f62097916727f77dc737dac2e8748 to your computer and use it in GitHub Desktop.
Save gizzmo/9f7f62097916727f77dc737dac2e8748 to your computer and use it in GitHub Desktop.
Wanted to try my hand a mocking the PHP Google API. Am I doing this right?
<?php
namespace Tests\Unit;
use Tests\TestCase;
class GoogleMailRepositoryTest extends TestCase
{
public function testFindsMessage()
{
$mGoogle_Service_Gmail = $this->createMock(\Google_Service_Gmail::class);
$mGoogle_Service_Gmail->users_messages =
tap($this->createMock(\Google_Service_Gmail_Resource_UsersMessages::class), function($mock) {
$mGoogle_service_GmailMessage = tap($this->createMock(\Google_Service_Gmail_Message::class), function($mock) {
$mock->method('getId')->willReturn('123456789');
$mock->method('getPayload')->willReturn(
tap($this->createMock(\Google_Service_Gmail_MessagePart::class), function($mock) {
$mock->method('getBody')->willReturn(
tap($this->createMock(\Google_Service_Gmail_MessagePartBody::class), function($mock) {
$mock->method('getData')->willReturn(
strtr(base64_encode('Body for message 123456789'), '+/', '-_')
);
})
);
})
);
});
$mock->method('listUsersMessages')->willReturn(
tap($this->createMock(\Google_Service_Gmail_ListMessagesResponse::class), function($mock) use ($mGoogle_service_GmailMessage) {
$mock->method('getMessages')->willReturn([
$mGoogle_service_GmailMessage
]);
})
);
$mock->method('get')->willReturn($mGoogle_service_GmailMessage);
});
$mail = new \App\Services\Google\MailRepository($mGoogle_Service_Gmail);
$this->assertAttributeInstanceOf(\Google_Service_Gmail::class, 'service', $mail);
$messages = $mail->find('query:string');
$this->assertInstanceOf(\Illuminate\Support\Collection::class, $messages);
$message = $messages->first();
$this->assertInstanceOf(\App\Services\Google\MailMessage::class, $message);
$this->assertEquals('123456789', $message->getId());
$this->assertEquals('Body for message 123456789', $message->getBody());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment