php - 断言两个数组相等但显示数组相同而没有区别?
问题描述
我正在尝试通过一个测试,该测试涉及运行一个返回一系列登录名的查询,以测试两个数组在测试中是否相等。
在过去,我尝试更改查询的格式以使测试通过以及编辑数组,最终它等于两个数组。不幸的是,测试仍然没有通过。
执行查询以获取一系列登录日期的函数:
public function getLogins(): array
{
return $this->createQuery()
->select('date AS datetime, COUNT(id) as total')
->orderBy('datetime', 'DESC')->groupBy('datetime')
->where('date >= -24 hours')
->getQuery()
->getResult();
}
这是测试类中的方法:
public function testGetLogins()
{
$dateLogins = $this->repository->getLogins();
$this->assertCount(4, $dateLogins, "Four instances");
$this->assertEquals([
["datetime" => new \DateTime("now -3 minutes"), "total" => "1"],
["datetime" => new \DateTime("now -7 days"), "total" => "1"],
["datetime" => new \DateTime("now -1 year"), "total" => "1"],
["datetime" => new \DateTime("now -600 days"), "total" => "1"]
], $logins, "The login instances returned match the expected times");
}
我期待测试通过,但它显示的是:
预期的和实际的数组都是相等的,所以我不确定是什么导致了测试失败。
解决方案
\DateTime
格式还包含有关秒的信息。new \DateTime("now -3 minutes")
将返回now
减去3 minutes
但准确的数量seconds
,这将始终不同,具体取决于您启动测试的时间。显然你想比较直到分钟的日期,所以你必须在比较之前格式化你的日期,因此你必须分别比较每个集合:
$expectedValues = [
["datetime" => new \DateTime("now -3 minutes"), "total" => "1"],
["datetime" => new \DateTime("now -7 days"), "total" => "1"],
["datetime" => new \DateTime("now -1 year"), "total" => "1"],
["datetime" => new \DateTime("now -600 days"), "total" => "1"]
];
for ($i = 0; $i < count($expectedValues); ++$i) {
$actualDate = (new \DateTime($logins[$i]['datetime']))->format('Y-m-d H:i');
$expectedDate = ($expectedValues[$i]['datetime'])->format('Y-m-d H:i');
$this->assertEquals($expectedDate, $actualDate);
$this->assertEquals($expectedValues[$i]['total'], $logins[$i]['total']);
}
推荐阅读
- linux - Linux 可执行文件格式。规范在哪里?
- javascript - 如何从捕获的异常循环中返回值?
- python - 如何使用 python 求解和绘制特定方程?
- vba - 如果另一个字段的值等于特定字符串,则使复选框消失
- c++ - 通过C ++ ODB将汉字插入mysql时出现问题
- javers - javers中的jql查询参数不支持不区分大小写的搜索
- python - 根据条件从同一数据框中查找行
- python - 获取所有标签具有特定类别的标签
- apache-spark - 提交作业时如何在火花作业中从外部路径外部化和加载属性文件
- firebase - 如何修复“必须初始化变量‘图像’”