我有一個測驗失敗,因為我無法成功存根get控制器的方法:
1) Tests\my-project\BackendBundle\Service\PdfGenerateServiceTest::test_getHttpPathToPtImage_should_return_the_default_avatar_when_photo_is_null
TypeError: Argument 1 passed to Mock_Pdf_d0288d34::setLogger() must implement interface Psr\Log\LoggerInterface, null given, called in /var/www/my-project/src/my-project/BackendBundle/Service/PdfGenerateService.php on line 66
考試
public function test_getHttpPathToPtImage_should_return_the_default_avatar_when_photo_is_null()
{
$protocolAndHost = "http://foo.bar.com";
$service = new PdfGenerateService($this->createFileServiceMock(), $this->createTranslatorMock(), $this->createSnappyMock(), $this->createContainerMock(), $protocolAndHost);
$httpPathToPtImage = $service->getHttpPathToPtImage(null);
self::assertEquals($httpPathToPtImage, $protocolAndHost . "abc/def");
}
失敗的建構式
public function __construct(FileService $fileService, Translator $translator, Pdf $snappy, ContainerInterface $container, string $protocolAndHost)
{
$this->fileService = $fileService;
$this->translator = $translator;
$this->currentLocale = $this->translator->getLocale();
/* Could reconfigure the service using `service.yml` to pass these in using DI */
$this->twig = $container->get('twig');
$this->logger = $container->get('logger'); // <--- should not be null
$timeoutInSeconds = 15; // can be high, since the job is done async in a job (user does not wait)
$snappy->setLogger($this->logger); // <--- THIS FAILS due to $this->logger being null
存根
protected function createContainerMock()
{
$containerMock = $this->createMock('Symfony\Component\DependencyInjection\ContainerInterface');
$loggerMock = $this->createLoggerMock();
$containerMock->method('get')->will($this->returnValueMap([
['logger', $loggerMock]
]));
return $containerMock;
}
我真的不明白為什么當我使用上面的呼叫設定要回傳的模擬時get('logger')呼叫才回傳。nullreturnValueMap
偶然地,我剛剛發現了一個關于此主題的 SO 問題,其中有人提到您需要提供所有引數,甚至是可選引數。然后我檢查了界面,它確實列出了第二個引數:
public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE);
盡管如此,將地圖更改為['logger', null, $loggerMock]沒有改變,所以我對接下來要嘗試的內容感到有些茫然。
Phpunit 6.5、PHP 7.2、Symfony 3.4
uj5u.com熱心網友回復:
你真的很接近解決方案。為 中的可選引數提供值時returnValueMap,您必須使用該值本身,而不僅僅是 null。
所以代替
['logger', null, $loggerMock]
嘗試指定
['logger', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $loggerMock]
完整的呼叫如下所示:
$containerMock->method('get')->will($this->returnValueMap([
['logger', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $loggerMock]
]));
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/401786.html
標籤:symfony phpunit symfony-3.4
