【发布时间】:2019-05-12 04:29:38
【问题描述】:
我再次向你们求助,因为我在这个“任务”上花费了相当多的时间,但我仍然无法弄清楚如何测试我的服务方法,没有我在数据库上的函数连接(我必须模拟存储库函数)
这是我的服务功能
public function getInfo($history, $name)
{
$requestRepository = $this->em->getRepository(Request::class);
if ($history) {
$requests = [];
foreach ($requestRepository->getRequestsByName($name) as $request) {
$requests[] = $requestRepository->transform($request);
}
return $requests;
} else {
$request = $requestRepository->getCompletedRequestByName($name);
if (!is_null($request)) {
return $requestRepository->transform($request);
} else {
return null;
}
}
}
这是我的测试
public function testGetInfo()
{
/* This returns errors, because it tries to connect to DATABASE, but I don't wan't that, that's why I figure out I need to mock this
$requestManager = new RequestManager($this->entityManager);
$test = $requestManager->getInfo('histroy', 'antrax.com');
*/
$requestManager = $this->getMockBuilder(RequestManager::class)->disableOriginalConstructor()->setMethods(['getInfo'])
->getMock();
// And rest of this are just my FAILED attempts to figure out, how to test my methods
$queryBuilder = $this->getMockBuilder(RequestRepository::class)->disableOriginalConstructor()
->setMethods(['getInfo'])->getMock();
$test = $queryBuilder->method('getInfo')->willReturnSelf();
$queryBuilder->method('getInfo')->willReturnCallback(function ($field, $value) use ($queryBuilder, $test){
if ($field == 'newStatus') {
$this->assertSame('EXPIRED', $value);
}
return $queryBuilder;
});
}
请有人帮助我如何为我的方法 getInfo 编写一个测试,以便它有 100% 的覆盖率。如果您需要任何其他信息,请告诉我,我会提供。谢谢!
【问题讨论】:
-
您正在函数内创建存储库。我认为这就是为什么你无法让它像你想要的那样工作的主要原因。我将使存储库成为在您的构造函数中初始化的变量,以便您可以轻松地模拟存储库。嘲笑
requestManager没有多大意义,因为这是您要测试的东西。
标签: symfony service doctrine-orm phpunit symfony4