Testing
A bot is a function from updates to Bot API calls, which makes it pleasant to test. Give the bot a fake transport that records requests and returns canned responses, feed it update arrays with $bot->handle(), and assert on the calls it made. No token, network, or Telegram account is needed.
A recording transport
Section titled “A recording transport”<?php
declare(strict_types=1);
namespace Tests\Support;
use Pam\Telegram\Transport\Response;use Pam\Telegram\Transport\Transport;
final class RecordingTransport implements Transport{ /** @var list<array{method: string, params: array<string, mixed>}> */ public array $calls = [];
/** @var list<Response> */ private array $queue = [];
public function willReturn(mixed $result): self { $this->queue[] = new Response(200, json_encode(['ok' => true, 'result' => $result]));
return $this; }
public function request( string $method, string $url, array $headers, string $body, float $timeout, int $maxResponseBytes, ): Response { $this->calls[] = [ 'method' => basename($url), 'params' => json_decode($body, true) ?? [], ];
return array_shift($this->queue) ?? new Response(200, '{"ok":true,"result":true}'); }}Requests without uploads are sent as JSON, so json_decode($body) gives you the parameters. Uploads with InputFile use multipart bodies instead.
Writing tests
Section titled “Writing tests”Build the bot in a small factory that your entry point and your tests both use, then pass the fake transport and a dummy token in tests. Set username: so command mentions are checked without a getMe call:
<?php
declare(strict_types=1);
namespace Tests\Unit;
use Pam\Telegram\Bot;use Pam\Telegram\Context;use Pam\Telegram\Scene;use PHPUnit\Framework\TestCase;use Tests\Support\RecordingTransport;
final class BotTest extends TestCase{ private RecordingTransport $transport;
private Bot $bot;
protected function setUp(): void { $this->transport = new RecordingTransport(); $this->bot = new Bot('123456:TEST-TOKEN-0000000000000000', $this->transport, username: 'acme_bot');
$this->bot->command('start', fn (Context $ctx) => $ctx->reply('Welcome, '.$ctx->from()['first_name'])); $this->bot->scene('signup', function (Context $ctx, Scene $scene): void { $ctx->reply('What is your email?'); $scene->next(); }, function (Context $ctx, Scene $scene): void { $ctx->session['email'] = $ctx->text(); $ctx->reply('Thanks!'); $scene->leave(); }, ); $this->bot->command('signup', fn (Context $ctx) => $ctx->enter('signup')); }
public function testStartGreetsTheUser(): void { $this->bot->handle($this->command(1, '/start'));
self::assertSame('sendMessage', $this->transport->calls[0]['method']); self::assertSame(42, $this->transport->calls[0]['params']['chat_id']); self::assertSame('Welcome, Alice', $this->transport->calls[0]['params']['text']); }
public function testSignupAsksForTheEmailAndThanks(): void { $this->bot->handle($this->command(1, '/signup'));
self::assertSame( ['What is your email?', 'Thanks!'], array_map(fn (array $call) => $call['params']['text'], $this->transport->calls), ); }
/** @return array<string, mixed> */ private function message(int $id, string $text, array $extra = []): array { return ['update_id' => $id, 'message' => [ 'message_id' => $id, 'date' => 1_700_000_000, 'chat' => ['id' => 42, 'type' => 'private'], 'from' => ['id' => 42, 'is_bot' => false, 'first_name' => 'Alice'], 'text' => $text, ] + $extra]; }
/** @return array<string, mixed> */ private function command(int $id, string $text): array { $length = strlen(explode(' ', $text)[0]);
return $this->message($id, $text, ['entities' => [ ['type' => 'bot_command', 'offset' => 0, 'length' => $length], ]]); }}pam vendor/bin/phpunitTesting webhooks and errors
Section titled “Testing webhooks and errors”handleWebhook() returns the HTTP status, which makes the security checks easy to assert:
$bot = new Bot('123456:TEST-TOKEN-0000000000000000', $transport, webhookSecret: 'test-secret');
self::assertSame(401, $bot->handleWebhook('{"update_id":1}', 'wrong-secret'));self::assertSame(400, $bot->handleWebhook('not json', 'test-secret'));self::assertSame(200, $bot->handleWebhook('{"update_id":1}', 'test-secret'));To simulate Telegram errors, return a failed response from your transport, for example new Response(403, '{"ok":false,"error_code":403,"description":"Forbidden: bot was blocked by the user"}'), and assert that your code catches the resulting TelegramException.