0
votes

I'm learning codeigniter 4 and trying to build some test to my controller. I try to test my post method for my controller and create request instance and change to post method like the following CodeIgniter 4 Documentation : withRequest but I got errors like this:

There was 1 error:

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

Why the error says uri, userAgent that in documentation just give example uri parameter? And when I look in URI class _construct I just need one argument $uri.

Any help?

Here is my code in controller test :

$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'));

My full controller test

1

1 Answers

0
votes

Whenever you are performing the Feature Testing using Command Line, It will never return the userAgent. So you have to mock the Request as well as the such as Authentication.

Following is the way I have approached Feature Testing.

In the setUp method, I have remapped the URL of the API for Testing. Additionally, I have mocked my Authentication service as well.

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

Then when testing the API in the method I do as following:

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
    }

Here $this->withRoutes returns the mock of the URI routing which is provided by CI4. There might be a better implementation as well since I am currently learning Unit Testing as well.

Reference: https://codeigniter4.github.io/userguide/testing/feature.html