duandao1931 2018-01-17 09:27
浏览 58
已采纳

在Symfony 3.4中对单元测试中的服务进行模拟

I have a simple DefaultController as service, where the DI is autowired.

class DefaultController extends BaseController
{
    private $logger;
    private $recordRepository;

    public function __construct(LoggerInterface $logger, RecordRepository $recordRepository)
    {
        $this->logger = $logger;
        $this->recordRepository = $recordRepository;
    }

    public function downloadAction($uuid)
    {
        $recordRepo = $this->recordRepository;

        $record = $recordRepo->findActive($uuid);

        $logger = $this->logger;

        if (!$record) {
            $logger->error('Record not found: '.$uuid);

            return $this->render('default/download_error.html.twig', [
                'error' => 'record_not_found'
            ]);
        }
    }
}

I've written a unit test that tries to call this method while also replacing one of the services (the logger) with a mock:

<?php
namespace Tests\AppBundle\Controller;

use Monolog\Logger;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase {

    public function testDownloadAction()
    {
        $mock = $this->getMockBuilder(Logger::class)
            ->disableOriginalConstructor()
            ->getMock();

        $mock->expects($this->once())->method('error')
            ->with('Record not found: 1223');

        $client = static::createClient([]);

        $client->getContainer()->set('logger', $mock);

        $client->request('GET', '/download/12233');

        print $client->getResponse()->getContent();

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
    }

}

The problem is, when this test fails (because the logger error and expected string dont match up), the PHPunit message is put in the $client->getResponse output instead of being caught in the CLI.

Output CLI:

PHPUnit 4.8.36 by Sebastian Bergmann and contributors.
F<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta name="robots" content="noindex,nofollow" />
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <title>    Expectation failed for method name is equal to &lt;string:error&gt; when invoked 1 time(s) Parameter 0 for invocation Monolog\Logger::error(&#039;Record not found: 12233&#039;, Array ()) does not match expected value. Failed asserting that two strings are equal. (500 Internal Server Error) </title> 

(further long webpage output removed here)

PHPUnit message:

There was 1 failure:

1) Tests\AppBundle\Controller\DefaultControllerTest::testDownloadAction
Failed asserting that 500 matches expected 200.

Do I have to use a regular PHPUnit case if I want to use mock objects? In that case I should probably refactor the $this->render in the Controller as well.

  • 写回答

1条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 session失效问题
      • ¥15 GMS地下水数值模拟无法打开
      • ¥15 树型结构的数据怎么匹配分支
      • ¥15 stm32F4用.引不出来结构体成员怎么解决
      • ¥15 .exe文件打不开怎么解决?
      • ¥30 Syntax Error: TypeError: this.getOptions is not a function的问题
      • ¥15 eclipse Android环境搭建
      • ¥15 unity中脚本之间的继承有什么作用
      • ¥15 C语言内存对齐代码不太理解
      • ¥15 uniapp中的uni-file-picker组件多图上传,删除,显示。以及C#.Net后端处理问题