如何将参数传递给模拟的 class 构造函数
How to pass arguments to a mocked class constructor
我的 class 中有一个方法 (getUsers()
) 我想模拟,但我的 class 中有一个构造函数。模拟 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));
}
}
例如,我想将日期“2021-12-22”传递给构造函数,以便 getDay() 方法 returns 22 而不是当前日期。
我之前没有使用过 PHPUnit 模拟(通常默认为 Mockery)但是看看 the documentation 你能在 getMockBuilder
上调用 setConstructorArgs(array $args)
吗?
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));
}
}
我的 class 中有一个方法 (getUsers()
) 我想模拟,但我的 class 中有一个构造函数。模拟 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));
}
}
例如,我想将日期“2021-12-22”传递给构造函数,以便 getDay() 方法 returns 22 而不是当前日期。
我之前没有使用过 PHPUnit 模拟(通常默认为 Mockery)但是看看 the documentation 你能在 getMockBuilder
上调用 setConstructorArgs(array $args)
吗?
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));
}
}