【发布时间】:2020-05-01 23:03:20
【问题描述】:
基本上我想测试,当我调用一个方法 2 次时,另一个方法被调用一次,但我得到以下异常:
嘲弄\异常\BadMethodCallException:收到 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([]);
}
}
主机存储库:
[...]
/**
* @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...
【问题讨论】:
-
$this->getDimensionByName(是做什么的?那里有没有可以模拟的调用来检查它是否被多次调用? -
getEnvironmentsHostList调用getThinClientDimension调用getDimensionByName(我模拟或试图模拟) -
但是
getThinClientDimension是你HostRepository的一个函数? -
我的错,我忘了在问题中将它们分开,方法
getThinClientDimension在DimensionRepositoy中
标签: laravel eloquent mocking laravel-6 mockery