【问题标题】:Error: Call to undefined method get() in PHPUnit Symfony错误:在 PHPUnit Symfony 中调用未定义的方法 get()
【发布时间】:2021-12-31 09:32:19
【问题描述】:

我正在尝试使用 PHPUnit 9.0.0 和 Symfony 5.1.8 执行我的第一个单元测试。如果 HTTP 响应为 200,则此测试必须通过。

<?php declare(strict_types=1);

namespace Tests\Infrastructure\Api\Controller;

use PHPUnit\Framework\TestCase;

class ControllerTests extends TestCase
{
    /** @test */
     public function route(): void
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    
    }

}

我得到错误:

有 1 个错误:

  1. Tests\Infrastructure\Api\Controller\SupplierControllerTests::route 错误:调用未定义的方法 Tests\Infrastructure\Api\Controller\SupplierControllerTests::get()

我以为 Get 方法是默认方法,由 PHPUnit\Framework\TestCase 导入,但看起来不是这样。

我必须在我的类 ControllerTests 中添加一个 Get 方法吗?如何开发它来测试 HTTP 响应?

提前致谢

【问题讨论】:

    标签: php symfony get phpunit


    【解决方案1】:

    你需要扩展 Symfony 提供的 WebTestCase,而不是 PHPUnit 提供的默认 TestCase。

    这是您尝试编写的类似测试的示例:

    namespace App\Tests\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
    
    class PostControllerTest extends WebTestCase
    {
        public function testShowPost()
        {
            $client = static::createClient();
    
            $client->request('GET', '/post/hello-world');
    
            $this->assertEquals(200, $client->getResponse()->getStatusCode());
        }
    }
    

    【讨论】:

    • 所以我必须使用另一个命令来抛出测试? (其实我用的是./vendor/bin/phpunit)
    • 我说是因为我收到错误:“ Tests\Infrastructure\Api\Controller\ControllerTests::route RuntimeException: Class "App\Kernel" 不存在或无法自动加载。检查 KERNEL_CLASS phpunit.xml 中的值与内核的完全限定类名匹配,或者覆盖“Tests\Infrastructure\Api\Controller\ControllerTests::createKernel()”方法。”。我正在寻找原因,但我没有找到。
    猜你喜欢
    • 2020-09-03
    • 2019-04-20
    • 2016-04-21
    • 2016-12-23
    • 2017-06-11
    • 2018-03-22
    • 2011-07-17
    • 1970-01-01
    相关资源
    最近更新 更多