PHP: how to make test static methods

I decided to create my own ORM structure for the poor. Since I did not know how to do this, I decided to develop before testing. Github . After it works the way I want, I understand that my code was unstable due to the tight connection of my static methods with the query class and BaseModel.

So I thought of some ways to check:

  • So that each request method gets an obect connection: But this means that when I try to use this method in the BaseModel class, I still have to tightly connect the connection object to the base module.
  • Leave it like this: it means that during testing PHPUnit I will have to override BaseModel.

In any way, I feel that I am not doing the right thing. I believe that there is a better way to do this work, and I need your helpers. Thanks

+4
source share
2 answers

A quote from Mishko Hevery in Statics is death for testing :

. , - , , . , / /, -, . . , , , .

:

, , , , . .

TL; DR: , .

:

, , , . -

public static function setQueryClass($className) {
    static::queryClass = $queryClass;
}

StaticSQLQuery $className. , StaticSQLQuery , . PHP7 :

BaseClass::setQueryClass(
    get_class(new class extends StaticSQLQuery {
        public static function init()
        {
            return 'My stub';
        }
    })
);

PHP7 :

class StaticSQLQueryMock extends StaticSQLQuery
{
    public static function init()
    {
        return 'My stub';
    }
}

BaseClass::setQueryClass(StaticSQLQueryMock::class);
+3

, : https://github.com/shagabutdinov/moka

, :

$classMock = \shagabutdinov\Moka::mockClass('MyClass', ['::method' => 'RESULT']);
$classMock::method('ARG1'); // RESULT
$classMock::method('ARG2'); // RESULT
$classMock::moka->report('method'); // [['ARG1', 'ARG2']]
0

Source: https://habr.com/ru/post/1620973/


All Articles