Does Phpunit work with Structured Programming?

Asked

Viewed 117 times

2

Good morning, I have a college job that you should do unit tests, and for that I am using Phpunit, the small application that I created to perform these tests is composed only by structured programming (without object orientation) but in every tutorial I ended up finding on Youtube they just demonstrate applications using object orientation.

I wonder if I can still do unitary tests with this application programmed structurally or will I have to switch to an Object Oriented to finish my work? If there is no other unit test tool in PHP that can perform tests in a structured application?

Thank you.

1 answer

2


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

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 the method has been declared _execute who accepts a array of GET parameters, where the same capture and return instead of including in each one several times. Soon after it is compared the output using the methods of assertionof Phpunit.

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

And of course when testing, you should put the error_reporting as E_ALL | E_STRICT.

source: https://stackoverflow.com/questions/5021254/php-testing-for-procedural-code

  • Perfect! Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.