hermeslin/mockery-overload-properties

通过Mockery的重载关键字模拟mock实例的属性

v1.0.1 2018-02-25 10:57 UTC

This package is not auto-updated.

Last update: 2024-09-29 05:01:51 UTC


README

通过Mockery的重载关键字模拟mock实例的属性

安装

使用composer安装mockery-overload-properties

$ composer require --dev hermeslin/mockery-overload-properties

测试遗留代码示例

example文件夹下,您可以看到我们想要测试的示例代码

  1. User.php
  2. Vip.php

您将在Vip.php中找到硬依赖。

硬依赖不是什么大问题,您可以使用Mockery的overload关键字轻松模拟User实例,但模拟在User__construct阶段设置的属性则比较困难。

测试用例

tests文件夹下,这里有两个测试用例

  1. LegacyCodeFailTest.php
  2. LegacyCodeSuccessTest.php

查看tests\LegacyCodeSuccessTest.php将向您展示如何使用mockery-overload-properties来模拟User

    /**
     * @test
     */
    public function notVipUserBonusShouldCorrect()
    {
        $properties = [
            'id' => 2,
            'isVip' => false,
            'rank' => 99
        ];
        $user = mop::mock('\User', $properties);

        // bounus should be 149
        $bunus = 100 * 0.5 + 99;

        $vip = new Vip;
        $this->assertEquals($bunus, $vip->bonus($userId = 2));
    }

当模拟带有属性的实例时,您仍然可以使用MockeryExpectation Declarations来测试您的代码。

    /**
     * @test
     */
    public function notVipUserBonusShouldCorrect()
    {
        $properties = [
            'id' => 2,
            'isVip' => false,
            'rank' => 99
        ];
        $user = mop::mock('\User', $properties);

        // Expectation
        $user->shouldReceive('name_of_method');
            ->with($arg1, $arg2, ...);
            ->andReturn($value);

        // etc...
    }