【问题标题】:PhpUnit testing method with that have variable argument array具有可变参数数组的 PhpUnit 测试方法
【发布时间】:2018-08-05 16:59:37
【问题描述】:

我的场景是我正在测试一个方法,该方法从一个库中调用另一个方法,该库采用一个带有两个键 ['id'=>123, 'timestamp'=>microtime()] 的数组。我可以将此微时间作为我正在测试的方法的参数,但有没有一种方法可以进行此测试,以便我测试除某些键之外的所有键对于被调用的方法是相等的。

     $this->foobarLibary->expects($this->once())
                ->method('saveItem')
                ->with(['id'=>1, 'timestamp'=>microtime()])
                ->willReturn(200);

       $res =  $this->sut->sutMethodThatCallsFoobarSaveItem();

       $this->assertTrue($res);

我抱怨timestamp 键不相等,这是真的,因为微时间不同。

此测试现在失败,因为时间不能相等。有解决办法吗?

【问题讨论】:

  • 显示测试的功能,也许这有帮助。测试本身并不过分。
  • sutMethodThatCallsFoobarSaveItem 是正在测试的函数。

标签: php unit-testing mocking phpunit


【解决方案1】:

如果你使用 Symfony(或者你可以使用phpunit-bridge)我建议你看看ClockMock feature

此桥提供的ClockMock 类允许您模拟 PHP 的内置时间函数time()microtime()sleep()usleep()

你可以阅读here 了解在没有 Symfony 框架的情况下使用

希望有帮助

【讨论】:

  • 您好,感谢您对此发表评论。我在这里没有使用 symfony 框架。但是这个phpunit-bridge 看起来很有希望。我会看看这个。
猜你喜欢
  • 2021-10-19
  • 2014-07-06
  • 2012-10-13
  • 2018-05-28
  • 2021-12-04
  • 1970-01-01
  • 2018-03-01
  • 2017-08-25
  • 1970-01-01
相关资源
最近更新 更多