Как я могу проверить метод, вызываемый один раз - PullRequest
0 голосов
/ 15 января 2020

В основном я хочу проверить, что, когда я вызываю метод 2 раза, другой метод вызывается один раз, но я получаю следующее исключение:

Mockery \ Exception \ BadMethodCallException: Received Mockery_0_App_Repository_DimensionRepository :: getThinClientDimension () , но ожидания не были указаны

Мой тест выглядит следующим образом

class HostRepositoryTest extends TestCase
{
/**
 * @var HostRepository
 */
private $hostRepository;

/**
 * @var Dimension
 */
private $dimension;

public function setUp(): void
{
    parent::setUp();
    $this->dimension = new Dimension();
    $mockDimensionRepository = Mockery::mock(DimensionRepository::class);
    $mockDimensionRepository->shouldReceive('getDimensionByName')
        ->once()
        ->andReturn($this->dimension);
    $this->hostRepository = new HostRepository($mockDimensionRepository);
}

/**
 * Test lazy loading dimension retrieval
 */
public function testGetThinClientDimension()
{
    $this->hostRepository->getEnvironmentsHostList([]);
    $this->hostRepository->getEnvironmentsHostList([]);
}
}

HostRepository:

[...]
/**
 * @param $configurationIds
 * @return Host[]|Collection
 */
public function getEnvironmentsHostList($configurationIds)
{
    //dd('test'); If I uncomment this it will be executed in the test
    $hostDimension = $this->dimensionRepository->getThinClientDimension();
    dd($hostDimension); // This is not executed if the test is ran
    //Returns an entity through Eloquent ORM
    [...]
}

DimensionRepositoy:

class DimensionRepository
{
private $thinClientDimension;

const THINCLIENT = 'ThinclientId';

[...]

public function getDimensionByName($name)
{
    return Dimension::where(['Name' => $name])->firstOrFail();
}

/**
 * Lazy load Thinclient dimension
 * @return Dimension
 */
public function getThinClientDimension()
{
    dd('test'); // This part is not executed when running the test which I find weird
    if ($this->thinClientDimension === NULL) {
        $this->thinClientDimension
            = $this->getDimensionByName(self::THINCLIENT);
    }
    return $this->thinClientDimension;
}
[...]

Обновление:

Похоже, что когда я звоню $this->dimensionRepository->getThinClientDimension()getEnvironmentsHostList), генерируется исключение.

Кажется, я должен также высмеять это (getThinClientDimension), что сделать мой тест бесполезным, потому что, как вы видите, он делегирует вызов смоделированному методу getDimensionByName ...

1 Ответ

0 голосов
/ 15 января 2020

Видимо, исправление было использовать makePartial() при издевательстве над объектом

public function setUp(): void
{
    parent::setUp();
    $this->dimension = self::getDimension();
    $this->mockDimensionRepository = $this->mock(DimensionRepository::class)->makePartial();
    $this->hostRepository = new HostRepository($this->mockDimensionRepository);
} 

LegacyMockInterface

/**
 * Set mock to defer unexpected methods to its parent if possible
 *
 * @return Mock
 */
public function makePartial();

Похоже, что этот модификатор сообщает Mockery, что он может вызывать другие методы, которые не являются поддельными (что должно быть по умолчанию на мой взгляд)

...