【问题标题】:You must supply the parameters: uri, userAgent. when create URI instance CodeIgniter 4您必须提供参数:uri、userAgent。当创建 URI 实例 CodeIgniter 4
【发布时间】:2021-04-07 05:52:03
【问题描述】:

我正在学习 codeigniter 4 并尝试为我的控制器构建一些测试。我尝试为我的控制器测试我的 post 方法并创建请求实例并更改为 post 方法,如下面的 CodeIgniter 4 Documentation : withRequest 但我得到了这样的错误:

There was 1 error:

1) Tests\Support\Controllers\UserControllerTest::testCreateUser
InvalidArgumentException: You must supply the parameters: uri, userAgent.

为什么错误说 uri, userAgent 在文档中只给出示例 uri 参数?当我查看 URI 类 _construct 时,我只需要一个参数 $uri。

有什么帮助吗?

这是我在控制器测试中的代码:

$request = new IncomingRequest(new \Config\App(), new URI("http://localhost:8080/users/create"));

        $criteria = $this->fabricator->make()->toArray();
        $criteria['password'] = 'masdika00';
        $request->setMethod('post');
        $request->setGlobal('post', $criteria);
        
        $postresult = $this->withRequest($request)
                        ->controller(Users::class)
                        ->execute('create');
        
        var_dump($request);
        $this->assertTrue($result->isOK());
        $this->assertTrue($result->see('welcome'));

我的完整controller test

【问题讨论】:

    标签: php codeigniter codeigniter-4


    【解决方案1】:

    每当您使用命令行执行功能测试时,它永远不会返回 userAgent。所以你必须模拟请求以及诸如身份验证之类的。

    以下是我进行功能测试的方式。

    在 setUp 方法中,我重新映射了用于测试的 API 的 URL。此外,我还模拟了我的身份验证服务。

    public function setUp(): void
    {
    $this->testing_routes = [[ 'post', 'create', 'MyController::create' ]];
    $this->authenticationMock = $this->getMockBuilder('Authentication')
            ->getMock();
    }
    

    然后在测试 API 的方法中我执行以下操作:

    public function test_authenticated_user_can_create_entry(){
    
            $this->authPolicy->method('checkAuth')->willReturn(true);
            $result = $this->withRoutes($this->testing_routes)->post('create', $fabricated_array);
            //assert
        }
    

    这里 $this->withRoutes 返回 CI4 提供的 URI 路由的模拟。可能还有更好的实现,因为我目前也在学习单元测试。

    参考:https://codeigniter4.github.io/userguide/testing/feature.html

    【讨论】:

    • 感谢您的回复,但在我当前的测试中,我使用 HTTP 测试文档中的功能测试而不是控制器测试
    • 我认为您错过了第一点。您不能直接测试 IncomingRequest 类。在文档中,他们没有使用 IncomingRequest。当您使用 CI4 自己的 FeatureTesting 类扩展 Test 类时,您必须模拟该请求,而 CI4 会为您执行此操作。
    猜你喜欢
    • 1970-01-01
    • 2021-09-30
    • 2020-11-22
    • 1970-01-01
    • 2020-01-07
    • 2022-06-24
    • 2015-10-15
    • 1970-01-01
    • 2019-01-15
    相关资源
    最近更新 更多