美文网首页
使用 ClockMock 进行和时间有关的单元测试

使用 ClockMock 进行和时间有关的单元测试

作者: forks1990 | 来源:发表于2021-12-04 20:07 被阅读0次

    日期有关的代码是比较难测试的,超时30分钟,不能真的等30分钟。在 php 生态中,个人觉得 ClockMock 是最好用的,

    1. Mock的日期功能最全面,
    2. 直接替换系统接口,不依赖中间接口做隔离

    ClockMock 是 Symfony phpunit bridge 中的一部分,在非 Symfony 项目中也可以使用。在标准的phpunit中使用时,需要注册test-listener,修改 phpunit 的配置文件:

    <!-- http://phpunit.de/manual/6.0/en/appendixes.configuration.html -->
    <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/6.0/phpunit.xsd"
    >
    
        <!-- ... -->
    
        <listeners>
            <listener class="Symfony\Bridge\PhpUnit\SymfonyTestsListener"/>
        </listeners>
    </phpunit>
    

    Mock 了 time(), microtime(), sleep(), usleep() gmdate() 系统函数。绝大多数时间操作都来自于这些函数,所以使用第三方库的代码也可以测试。

    它的内部实现原理是:调用函数时,如果这个函数已经定义在了当前的 namespace 中,则调用这个函数,否则调用全局函数。
    ``ClockMock::register(MyClass::class);实际的作用是通过eval()MyClass::class` 所在的 namespace 中注入这些时间函数。

    // the test that mocks the external time() function explicitly
    namespace App\Tests;
    
    use App\MyClass;
    use PHPUnit\Framework\TestCase;
    use Symfony\Bridge\PhpUnit\ClockMock;
    
    /**
     * @group time-sensitive
     */
    class MyTest extends TestCase
    {
        public function testGetTimeInHours()
        {
            ClockMock::register(MyClass::class);
    
            $my = new MyClass();
            $result = $my->getTimeInHours();
    
            $this->assertEquals(time() / 3600, $result);
        }
    }
    

    需要注意的是:当函数在注入前,已经在所在的 namespace 中调用,则 php 执行引擎使用已经调用过的(全局函数),而不理会
    新注入的函数(也许是性能考虑)。所以靠谱的办法是修改 phpunit.xml :

    <phpunit bootstrap="./tests/bootstrap.php" colors="true">
    
        <!-- ... -->
    
        <listeners>
            <listener class="\Symfony\Bridge\PhpUnit\SymfonyTestsListener">
                <arguments>
                    <array>
                        <element key="time-sensitive">
                            <array>
                                <element key="0">
                                    <string>Namespace\Need\Mocked1</string>
                                </element>
                                <element key="1">
                                    <string>Namespace\Need\Mocked2</string>
                                </element>
                            </array>
                        </element>
                    </array>
                </arguments>
            </listener>
        </listeners>
    </phpunit>
    
    

    这样在测试开始运行前,提前注入到相关的 namespace 中。


    Mock掉的时间,默认是 TestFixture 开始的时间,也可以手工调用 ClockMock::withClockMock(100) 强制到某个已知值,当通常并没有这个必要。

    相关文章

      网友评论

          本文标题:使用 ClockMock 进行和时间有关的单元测试

          本文链接:https://www.haomeiwen.com/subject/rylbxrtx.html