首页 > 解决方案 > kahlan - 单元测试不起作用 - 获取 - 异常`代码(0),消息“未定义变量`请求`

问题描述

我是 kahlan 单元测试的新手,我已经在 Symfony 上安装了它。尝试运行时出现以下错误 - vendor/bin/kahlan

C:\web\simple-symfony-api-v2\vendor\kahlan\kahlan\src\Scope.php错误:/category/list x 它显示类别列表在第 109 行抛出未捕获的异常

  message:`Exception` Code(0) with message "Undefined variable `request`."

代码:

namespace App\Spec\Controller;

describe('CategotyController', function() {
  describe('/category/list', function() {
    it('shows category list', function() {

      $request = $this - > request - > create('/category/list', 'GET');
      $response = $this - > kernel - > handle($request);

      var_dump($response);
    });
  });
});

标签: phpunit-testingsymfony4

解决方案


在测试、调试和阅读谷歌/文档后,我发现我丢失了 - kahlan-config.php - 这个文件需要添加到 Symfony 项目的根目录中。

代码:

<?php // kahlan-config.php 

use App\Kernel;
use Kahlan\Filter\Filters;
use Symfony\Component\HttpFoundation\Request;

Filters::apply($this, 'bootstrap', function($next) {

    require __DIR__ . '/vendor/autoload.php';

    $root = $this->suite()->root();
    $root->beforeAll(function () {
       $this->request = Request::createFromGlobals();
       $this->kernel  = new Kernel('test', false);
    });

    return $next();

});

推荐阅读