Search code examples
codeignitercodeigniter-4

Codeigniter 4 testing when controller method not found


I am doing HTTP testing in Codeigniter 4 and am getting the following error:

CodeIgniter\Exceptions\PageNotFoundException: Controller method is not found

The reason for this is I am trying to call a get() method on a route that only has a post (switching it to add results in a different response). That is correct. I am trying to make sure that the page returns 404 if someone tries to hack it. The problem is Codeigniter doesn't assert Status is 404 it simply falls over. Here is my code triggering:

$r = $this->withSession($session)->get($url);
$r->assertStatus(404);

Note the assert never runs! Instead I get the original error message. Surely I should be able to check for 404 routes (I've tried '404' instead of int) ?? Yes I could set a custom route that allowed Get but I want to test it as-is rather than what it isn't.

How do I get CI4 to accept my incorrect route as a 404?


Solution

  • My solution is to define a constant (IN_TESTING) for when I am testing and then edit system/Codeigniter run() function. This is of course amending the core system which some people won't like but until there is a fix (I am using 4.1.2) then this will suffice.

    catch (PageNotFoundException $e)
    {
        if (!defined('IN_TESTING') || IN_TESTING == false){
            $this->display404errors($e);
        } else {
        $this->router = Services::router($routes, $this->request);
    
        $path = $this->determinePath();
        $controller = $this->router->handle($path);
        $method     = $this->router->methodName();
    
        echo $path."\n".$controller."\n".$method;
        exit;
    
            $this->response->setStatusCode(404);
    
            return $this->response;
        }
    }
    

    Key tip if you do make changes to system files, track them! If you then need to run an upgrade you'll know what changes you've made.