首页 > 解决方案 > 断言两个数组相等但显示数组相同而没有区别?

问题描述

我正在尝试通过一个测试,该测试涉及运行一个返回一系列登录名的查询,以测试两个数组在测试中是否相等。

在过去,我尝试更改查询的格式以使测试通过以及编辑数组,最终它等于两个数组。不幸的是,测试仍然没有通过。

执行查询以获取一系列登录日期的函数:

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

我期待测试通过,但它显示的是:

测试输出

预期的和实际的数组都是相等的,所以我不确定是什么导致了测试失败。

标签: phparrayssymfonyphpunit

解决方案


\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']);
}

推荐阅读