如何为symfony控制器编写php单元测试用例

我正在尝试为symfony控制器编写一个单元测试用例.

控制器代码

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;

class Controller1 extends SecuredController
{

public function preExecute(Request $request) {
    parent::preExecute($request);
}

public function indexAction()
{
    return $this->render('help/index.html.twig');
}

我已经尝试编写如下所示的测试用例,但它会引发内部错误

namespace Tests\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class Controller1Test extends WebTestCase
{
public function testIndex()
 {
   $client = static::createClient();

    $response = $client->getResponse();

    $this->assertEquals(200, $response->getStatusCode());

}
}

任何建议对我都有帮助

最佳答案 首先,是UNIT测试.你这里不需要客户.你只需要你想要测试的课程.

namespace Tests\AppBundle\Controller;

use PHPUnit\Framework\TestCase;
use AppBundle\Controller\Controller1;

class Controller1Test extends TestCase
{
    public function testIndex()
    {
        $this->request = $this->getMockBuilder(
            'Symfony\Component\HttpFoundation\Request'
        )->disableOriginalConstructor()
        ->getMock();

        $controller = new Controller1();
        $controller->preExecute($this->request);
        $response = $controller->indexAction();
        $this->assertEquals(
            200,
            $response->getStatusCode()
        );
    }
}

例如,您的代码可能是

namespace Tests\AppBundle\Controller;

use Symfony\Component\HttpFoundation\Response;

class Controller1 extends SecuredController
{
    public function indexAction()
    {
        return new Response();
    }
}
点赞