我要测试的MyClass
类中的方法如下:
public function needs()
{
$domains = $this->em->getRepository(WebDomain::class)->findBy(array(
'client' => $this->client
));
$hosting = $this->em->getRepository(WebHosting::class)->findBy(array(
'client' => $this->client
));
if($domains !== null && $hosting !== null){
return true;
}
return false;
}
看着documentation of Symfony,我创建了一个像这样的测试:
public function testNeeds()
{
$em = $this->createMock(ObjectManager::class);
$client = new Client();
/**
* Add WebHosting to Client
*/
$webHosting = new WebHosting();
$webHosting->setClient($client);
/**
* Create a new WebDomain for Client/WebHosting
*/
$webDomain = new WebDomain();
$webDomain->setClient($client);
$webDomain->setWebHosting($webHosting);
我知道如何创建模拟存储库(例如所需的$domains
):
$domains = $this->createMock(ObjectRepository::class);
$domains->expects($this->any())
->method('findBy')
->willReturn($client->getWebDomain());
$em->expects($this->any())
->method('getRepository')
->willReturn($domains);
$myClass = new MyClass($client, $em);
因此,据我所知,这会创建一个模拟,每当调用方法findBy
时,都返回$domains
,但是我必须添加什么才能返回所需的$hosting
?
我怀疑它与$this->any()
有关,我认为我必须将其缩小到expects(WebDomain::class)
(这对c无效)。
由于我对Symfony中的UnitTests相当陌生(和一般而言),因此向我介绍正确的手册也可能会有所帮助。谢谢!
答案 0 :(得分:1)
在这种情况下,您应该根据传递给Repository
方法的参数返回不同的getRepository
。像这样:
$emMock
->method('getRepository')
->will($this->returnValueMap([
[WebDomain::class, $webDomainRepositoryMock),
[WebHosting::class, $webHostingRepositoryMock)
]));
注意:请记住为两个存储库配置findBy
。