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:

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)

            ->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>
        <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条回答 默认 最新

  • douyan8961 2018-01-17 10:12

    1) it's no need to write unit tests for controllers. If there is some login, then move it to Manager/Service/AnotherNameForLogicClass and tests it with unit test, but not controller 2) controllers are tested by functional/integrational tests and usually there is no need of mocks in this type of tests.

    There are different articles related to this topic. For example, from KNP: https://knpuniversity.com/screencast/symfony2-ep2/testing

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥40 图书信息管理系统程序编写
  • ¥15 7-1 jmu-java-m02-使用二维数组存储多元线性方程组
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题