PHP code example of mgleska / repositorymock

1. Go to this page and download the library: Download mgleska/repositorymock library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mgleska / repositorymock example snippets


// src/Service/SutService.php

class SutService
{
    public function __construct(
        private readonly Repository $repository,
    ) {
    }

    public function getFirst(): ?Entity
    {
        return $this->repository->find(1);
    }
}

// tests/Service/SutServiceTest.php

use RepositoryMock\RepositoryMockObject;
use RepositoryMock\RepositoryMockTrait;
...

class SutServiceTest extends TestCase
{
    use RepositoryMockTrait;

    private Sutservice $sut;

    private Repository|RepositoryMockObject $repository;

    protected function setUp(): void
    {
        $this->repository = $this->createRepositoryMock(Repository::class);

        $this->sut = new SutService(
            $this->repository,
        );
    }

    #[Test]
    public function getFirstFound(): void
    {
        $this->repository->loadStore([
            [ // values of selected properties of Entity
                'id' => 1,
                'name' => 'test',
            ],
        ]);

        $result = $this->sut->getFirst();

        $this->assertInstanceOf(Entity::class, $result);
    }

    #[Test]
    public function getFirstNotFound(): void
    {
        $this->repository->loadStore([
            [
                'id' => 22,
                'name' => 'test 22',
            ],
        ]);

        $result = $this->sut->getFirst();

        $this->assertNull($result);
    }
}