Welcome Guest, Not a member yet? Register   Sign In
phpunit testing routes only available after login
#4

(This post was last modified: 08-06-2023, 02:37 AM by dgvirtual. Edit Reason: code correction )

(08-05-2023, 03:56 PM)benedmunds Wrote: There’s not a great way. IonAuth really wasn’t the most testable bit of code since testing wasn’t big in CodeIgniter when it was originally written.

To do this you’d either need to mock the IonAuth->loggedIn() method.


I use IonAuth as a service, defined in my Config/Services.php, here is the method that defines the service:

PHP Code:
public static function ionAuth($getShared true)
{
    if ($getShared) {
        return static::getSharedInstance('ionAuth');
    }
    return new \IonAuth\Libraries\IonAuth();

So I was able to use the mocking services functionality as described in CI4 documentation.



With some help (and much misdirection) from Google Bard I came up with this thing that works:
PHP Code:
public function testValidateField()
{
    // case of user not being logged in:
    $route route_to('invoice_validate_field''date');
    $getArray = ['date' => '2023-01-03'];
    $result $this->call('get'$route$getArray);
    $this->assertTrue($result->isOK());
    $result->assertRedirect();
    $result->assertRedirectTo('login');

    // mock login
    $ionAuth $this->getMockBuilder('IonAuth\Libraries\IonAuth')
        ->setMethods(['loggedIn'])
        ->getMock();
    $ionAuth->expects($this->exactly(2)) // will have two checks
        ->method('loggedIn')
        ->willReturn(true);
      
    Services
::injectMock('ionAuth'$ionAuth);
  
    
// test without a validation error:
    // this->sess is an array of session variables, perhaps not actually needed here
    $result $this->withSession($this->sess)->call('get'$route$getArray);

    // assert that we no longer get redirect to login page:
    $this->assertFalse($result->isRedirect());
    // assert that the result does not include '„' symbol, which, in Lithuanian language,
    // surrounds the field name in error messages (alternative to checking for empty string)
    $result->assertDontSee('„');

    // lets introduce a wrong date to trigger validation error:
    $getArray = ['date' => '2023'];
    $result $this->withSession($this->sess)->call('get'$route$getArray);
    // again, no redirect here:
    $this->assertFalse($result->isRedirect());
    
    
// assert that we see part of Lithuanian error string:
    $result->assertSee('turi būti tiksliai 10 ženklų ilgio.');


Hope this will be useful for someone.


Thanks @benedmunds  and @kenjis for helping me reason through this.
==

Donatas G.
Reply


Messages In This Thread
RE: phpunit testing routes only available after login - by dgvirtual - 08-06-2023, 02:34 AM



Theme © iAndrew 2016 - Forum software by © MyBB