必须提供以下参数:URI,userAgent,创建URI示例时CodeIgniter 4

smdncfj3  于 2022-12-07  发布在  其他
关注(0)|答案(2)|浏览(148)

我正在学习codeigniter 4并尝试对我的控制器进行一些测试。我尝试为我的控制器测试post方法,并创建请求示例,然后更改为post方法,如以下CodeIgniter 4文档所示:withRequest但我得到如下错误:

There was 1 error:

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

为什么错误说uri,userAgent在文档中只给予示例uri参数?当我查看URI class _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

tquggr8v

tquggr8v1#

当你使用命令行执行功能测试时,它永远不会返回用户代理。所以你必须模拟请求以及诸如身份验证。
下面是我进行特性测试的方法。
在setUp方法中,我重新Map了测试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返回了CI 4提供的URI路由的模拟。可能还有更好的实现,因为我目前也在学习单元测试。
参考:https://codeigniter4.github.io/userguide/testing/feature.html

a11xaf1n

a11xaf1n2#

幸运地找到了答案。

<?php

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

/**
 * Syntax
 * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
 *
 * user agent strings
 * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox
 */
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:10.0) Gecko/20100101 Firefox/10.0';
$request = new IncomingRequest(new \Config\App(), new URI("http://localhost:8080/users/create"), 'php://input', new \CodeIgniter\HTTP\UserAgent());

// deprecated
// $request->setMethod('post');

$request->setGlobal('post', ['your-parameter-a' => 'parameter-value-of-a']);

// your code...

当你var_dump$this->request->getPost()在你的控制器里面时,预期的结果是:

array(3) {
  'your-parameter-a' =>
  string(20) "parameter-value-of-a"
}

相关问题