1

I am trying to test a procedural PHP file that begins with the if statement:

if ($_SERVER["REQUEST_METHOD"] == "POST") {

then proceeds to use the superglobal $_POST to get the variable which is then used in an SQL query.

Below is my PHPUnit code that I am trying to use to test the procedural file above:

<?php

use PHPUnit\Framework\TestCase;

require '../public_html/PHP/dbconfig.php';
//require '../public_html/PHP/getters/getBranchHeaderPhoto';

class getBranchHeaderPhotoTest extends TestCase {

    protected function setUp()
    {
        parent::setUp();
        $_POST = array();
    }

    /**
     * @test
     */
    public function checkThatGetBranchHeaderPhotoReturnsTheDirectoryAndImage() {
        $_SERVER["REQUEST_METHOD"] == "POST";
        $_POST = array("all");
        ob_start();
        include('../public_html/PHP/getters/getBranchHeaderPhoto.php');
        $contents = ob_get_contents();

        $this->assertNotNull($contents);
    }
}

?>

However, when I try and run the test in the command line, running the following cmd phpunit getBranchHeaderPhotoTest.php, the following error occurs;

There was 1 error:

1) getBranchHeaderPhotoTest::checkThatGetBranchHeaderPhotoReturnsTheDirectoryAndImage
Undefined index: REQUEST_METHOD

C:\Users\User\Documents\project\project\test\getBranchHeaderPhotoTest.php:21

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

I have tried following previous SO answers on this topic but can not pass a request method into the procedural file. Is this possible?

1 Answer 1

4

You're using == (comparison) when you want = (assignment). Change:

$_SERVER["REQUEST_METHOD"] == "POST";

to:

$_SERVER["REQUEST_METHOD"] = "POST";

If possible, fix the offending code to check the key exists, like with:

if (($_SERVER["REQUEST_METHOD"] ?? 'GET') == 'POST')
Sign up to request clarification or add additional context in comments.

1 Comment

Correct, mistake on my part. Have changed that to '=' rather than double '='. Consequently, the test outputs another error in that it cannot find the required file in the file I am testing, but it has certainly solved the Undefined Index error, so thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.