Summer Sale! All accounts are 50% off this week.

kleninmaxim's avatar

How I can write PhpUnit Tests on static class

For example, I have such static class

<?php

namespace Src;

class Time
{
    private static array $start;

    public static function up(float $seconds, string $prefix, bool $first = false): bool
    {
        if (!isset(self::$start[$prefix])) {
            self::$start[$prefix] = microtime(true) + $seconds;

            return $first;
        }

        return false;
    }

    public static function get(string $prefix): bool
    {
        return self::$start[$prefix];
    }
}
<?php

use PHPUnit\Framework\TestCase;

class Time extends TestCase
{
    /** @test */
    public function it_return_true_first_time()
    {
        $this->assertTrue(\Src\Time::up(1, 'test', true));
    }

    /** @test */
    public function it_return_false_first_time()
    {
        $this->assertFalse(\Src\Time::up(1, 'test'));
    }
}

When I run both tests, I have failed the second test, because it returns true. But when I run only it_give_false_first_time test, it is ok.

How I can write PhpUnit Tests on static class?

0 likes
4 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Add a teardown method that resets the static through a method on the class

public function tearDown()
{
    Time::reset(); //add a method to the class to reset it 
    parent::tearDown();
} 
kleninmaxim's avatar

@Sinnbeck Do you mean also such code to Src/Time Class at this example?

    public static function reset(): void
    {
        self::$start = [];
    }

Please or to participate in this conversation.