PhpUnit works with Structured Programming?

1

Good morning, I have a college job that you should do unit tests, and for this I am using PHPUnit, the small application that I created to perform these tests is composed only by structured programming (without object orientation) but throughout tutorial that I found on YouTube they just demonstrate applications using object orientation.

I wonder if I can do the unit tests anyway with this structured program application or will I have to switch to an Object Oriented to finish my work? If there is no other unit testing tool in PHP that can test in a structured application?

Thank you.

    
asked by anonymous 23.10.2018 / 15:17

1 answer

1

You can test non-OO code with PHPUnit, unit tests are not only linked to the Object Oriented paradigm, this type of test (as the name already says) tests the units of your code, in case OO is a method for example in your case may be a simple file with a code in there.

For example, you have this code: simple_add.php

$arg1 = $_GET['arg1'];
$arg2 = $_GET['arg2'];
$return = (int)$arg1 + (int)$arg2;
echo $return;

You can test it this way:

class testSimple_add extends PHPUnit_Framework_TestCase {

    private function _execute(array $params = array()) {
        $_GET = $params;
        ob_start();
        include 'simple_add.php';
        return ob_get_clean();
    }

    public function testSomething() {
        $args = array('arg1'=>30, 'arg2'=>12);
        $this->assertEquals(42, $this->_execute($args)); // passes

        $args = array('arg1'=>-30, 'arg2'=>40);
        $this->assertEquals(10, $this->_execute($args)); // passes

        $args = array('arg1'=>-30);
        $this->assertEquals(10, $this->_execute($args)); // fails
    }

}

For this example we have declared the _execute method that accepts an array of GET parameters, where it captures and returns instead of including in each one several times. Then the output is compared using the PHPUnit%% methods.

Of course, the third assertion will fail (depending on the error reported), because the script tested will return a assertion .

Of course, when testing, you should put Undefined index error as error_reporting .

source: link

    
23.10.2018 / 15:40