Testing

Learn how to test your integration.

When testing code that uses the SDK, you do not want to make real API calls. Because Plug is an interface, you can replace it with a mock that returns the values your test expects.

Unit testing

Type-hint the Plug interface in your controllers and services, then provide a mock in your tests.

This example mocks a content fetch with PHPUnit:

12345678910111213141516171819
<?php
use Croct\Plug\Plug;use Croct\Plug\FetchResponse;use PHPUnit\Framework\TestCase;
final class HeroServiceTest extends TestCase{    public function testBuildsHeadline(): void    {        $croct = $this->createMock(Plug::class);        $croct->method('fetchContent')            ->willReturn(new FetchResponse(['title' => 'Welcome']));
        $service = new HeroService($croct);
        $this->assertSame('Welcome', $service->headline());    }}

Feature testing

To test a request end-to-end, swap the Plug binding in the container with a mock so you control the responses.

Use mock before issuing the request:

1234567891011121314151617181920
<?php
namespace Tests\Feature;
use Croct\Plug\Plug;use Croct\Plug\FetchResponse;use Tests\TestCase;
final class HomePageTest extends TestCase{    public function testRendersHero(): void    {        $this->mock(Plug::class, function ($mock) {            $mock->shouldReceive('fetchContent')                ->andReturn(new FetchResponse(['title' => 'Welcome']));        });
        $this->get('/')->assertSee('Welcome');    }}

To exercise the real SDK against a mock server instead, point the base_endpoint_url at it in the test environment:

phpunit.xml
<php>    <env name="CROCT_BASE_ENDPOINT_URL" value="http://localhost:8080"/></php>

Both approaches keep your tests deterministic and isolated from the network.