mercredi 14 septembre 2016

how to test slim middleware response return (phpunit)

I created a Middleware wich should only redirect the user to an other Website (given in Request Url by the Parameter redirect)

class Middleware
{
    public function __invoke($request, $response, $next)
    {
        // Call next middleware or app
        $response = $next($request, $response);

        $redirectUrl = //get redirect url

        return $response->withStatus(200)->withHeader('Location', $redirectUrl);
    }
}

I already testet this and the Redirect works fine. So I came to that Point to write Unit-Tests. I failed ... This was my attempt:

class MiddlewareTest extends \PHPUnit_Framework_TestCase
{
    public $request = array(...); //inserted needed properties

    public function testInvoke(String $url) {
        $next = function () : bool
        {
            return true;
        }; //empty function
        $request['request']['scriptUri'] = "/parameterStuff&redirect=" . $url; //overwrite the Uri with provided Url
        $redirect = new Middleware($request, array(), $next);

        //just to test if result of response still empty
        $iCount = count((array)$redirect);
        $this->assertEquals(0, $iCount);

    }

    public function invokeProvider() : array
    {
        return array(
            array('http://example.com')
        );
    }
}

This test is successful but ofc it shouldn't... The return of this function should be a valid response. I tested this in my Browser and echo the return. It has a value there and it's the correct response with the expected Header. The return Value I receive in my Unit-Test is an empty object.

I red the Slim Documentation about the response Object and it sais:

This method returns a copy of the Response object that has the new header value. So I should definitely receive something from it. I also tried to return a copy of the response:

$copyresponse = response->withStatus(200)->withHeader('Location', $redirectUrl);
return $copyresponse;

This don't works as well. Any Idea what could cause my Problem and how to solve it?

Aucun commentaire:

Enregistrer un commentaire