【发布时间】:2015-07-20 03:30:11
【问题描述】:
我在 StackOverflow 上看到的大多数答案都没有使用 DateTime 对象,而是使用了 date() 函数。这使得它们的解决方案非常肮脏(覆盖date()、模拟被测对象的受保护函数等)。
有没有办法模拟DateTime,有效地模拟当前日期/时间?
例如,这是我要测试的代码:
public function __construct(UserInterface $user, EntityManager $manager)
{
$this->user = $user;
$this->manager = $manager;
}
public function create(Tunnel $tunnel, $chain, $response)
{
$history = new CommandHistory();
$history->setTunnel($tunnel)
->setCommand($chain)
->setResponse($response)
->setUser($this->user)
;
$this->manager->persist($history);
$this->manager->flush();
}
这是我在CommandHistory 班级中设置日期和时间的地方:
class CommandHistory
{
// Property definitions...
public function __construct()
{
$this->time = new \DateTime();
}
}
这是我的单元测试:
public function testCreate()
{
$user = new User();
$manager = $this->mockManagerWithUser($user);
$tunnel = $this->tunnel;
$chain = 'Commands`Chain';
$response = 'This is the response!';
$creator = new CommandHistoryCreator($user, $manager);
$creator->create($tunnel, $chain, $response);
}
protected function mockManagerWithUser(UserInterface $user)
{
$manager = \Mockery::mock('Doctrine\ORM\EntityManager');
$manager->shouldReceive('persist')->once()->with(\Mockery::on(function(CommandHistory $argument) use ($user) {
return
$argument->getCommand() === 'Commands`Chain'
&& $argument->getResponse() === 'This is the response!'
&& $argument->getTunnel() === $this->tunnel
&& $argument->getUser() === $user
;
}));
$manager->shouldReceive('flush')->once()->withNoArgs();
return $manager;
}
如您所见,我创建了一个相当冗长的闭包,只是为了排除包含当前时间的字段的比较,我觉得这会损害我的测试的可读性。
另外,为了让使用这个类的人保持易用性,我不想让他们在当前时间传递给create() 函数。我相信在我的类中添加奇怪的行为只是为了让它们可测试意味着我做错了。
【问题讨论】:
-
您在哪里使用当前时间?我对 PHP 不太熟悉,但我看不到任何地方使用的日期或时间是上面的任何代码...我假设它是 CommandHistory 对象的属性,您没有显示...跨度>
-
是的,在
CommandHistory的构造函数中。我刚刚也将其添加到我的问题中。谢谢提醒:-)
标签: unit-testing symfony datetime phpunit mockery