Is it possible to perform unit tests on PHP functions?

Asked

Viewed 44 times

0

With Phpunit we can perform unit tests in object-oriented code. There is something similar for PHP functions?

  • 1

    Of course yes, you write whatever you want within each test method, what is expected in the result is the value for the assert, it has no secret, phpunit can be written in OOP, but the content within each method can be anything.

  • Thank you @Guilhermenascimento. Based on your comment, I did some testing and came up with the answer I share for similar questions from other users.

1 answer

0

On the basis of Guilherme Nascimento commented, I did some tests and "discovered" that you can test functions with Phpunit.

I created a function called cfg_pdo_user()that must return a string with the value "root".

To test, I created a class MyTest with a method test_cfg_pdo_user()

<?php

use PHPUnit\Framework\TestCase;

class MyTest extends TestCase
{
    public function test_cfg_pdo_user()
    {
        $this->assertEquals('root', cfg_pdo_user());
    }
}

Then just run the command to run the tests:

PS C:\xampp\htdocs\mymoney> .\vendor\bin\phpunit --bootstrap .\init.php .\tests\MyTest.php

The option --bootstrap .\init.php included a file that includes the file with the tested function.

The result was as follows:

PHPUnit 9.0.1 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 84 ms, Memory: 4.00 MB

OK (1 test, 1 assertion)

Completion: it is possible to apply unit tests with Phpunit directly in functions, without relying on an object-oriented structure.

Browser other questions tagged

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