How to pass arguments to a mocked class constructor

Viewed 2187

I have one method (getUsers()) in my class that I would like to mock but I have a constructor in my class. How can I pass values to the constructor when mocking my class?

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));

    }

}

For example, I would like to pass the date "2021-12-22" to the constructor so the getDay() method returns 22 instead of the current day.

1 Answers

I haven't used PHPUnit mocks before (usually defaulting to Mockery) but looking at the documentation are you able to call setConstructorArgs(array $args) on the 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));

    }

}
Related