如何将参数传递给模拟类构造函数

时间:2021-03-08 23:09:02

标签: laravel phpunit

我的类中有一个方法 (getUsers()) 想要模拟,但我的类中有一个构造函数。模拟我的类时如何将值传递给构造函数?

class MyNotifications {

    /**
     * Date time.
     *
     * @var DateTime|mixed|null
     */
    public $date;

    public function __construct($date = NULL)
    {
        if (!$date) {
            $date = new \DateTime();
        }

        $this->date = $date;
    }

    /**
     * Get users.
     *
     * @param int $node_id
     *   Node id.
     *
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getUsers($node_id)
    {
        // API code goes here.
    }


    /**
     * Get day.
     *
     * @return false|int|string
     */
    public function getDay()
    {
        return $this->date->format('d');
    }

}

class MyNotificationsTest extends TestCase
{
    use RefreshMigrations;

    public function testOneDay()
    {
        $mock = $this->getMockBuilder(MyNotifications::class)->onlyMethods([
            'getUsers',
        ])->getMock();
        $mock->method('getUsers')->willReturn(['User 1']);

        dump($mock->getDay());
        dump($mock->getUsers(1));

    }

}

例如,我想将日期“2021-12-22”传递给构造函数,以便 getDay() 方法返回 22 而不是当前日期。

1 个答案:

答案 0 :(得分:1)

我之前没有使用过 PHPUnit 模拟(通常默认为 Mockery),但是看看 the documentation 你能在 setConstructorArgs(array $args) 上调用 getMockBuilder 吗?

class MyNotificationsTest extends TestCase
{
    use RefreshMigrations;

    public function testOneDay()
    {
        $mock = $this->getMockBuilder(MyNotifications::class)
        ->onlyMethods([
            'getUsers',
        ])
        ->setConstructorArgs(['2021-03-08'])
        ->getMock();
        $mock->method('getUsers')->willReturn(['User 1']);

        dump($mock->getDay());
        dump($mock->getUsers(1));

    }

}
相关问题