【问题标题】:Failed asserting two arrays are equal but shows that the arrays are the same with no difference?断言两个数组相等但显示数组相同而没有区别?
【发布时间】:2019-02-08 06:11:43
【问题描述】:

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

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

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

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

我希望测试通过,但它却显示如下:

Test Output

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

【问题讨论】:

  • new \DateTime 将创建一个对象,而不是从数据库返回的字符串。可能需要->format(...)。但是日期不会相等,因为"now -3 minutes" 每分钟都会改变。而且你没有在任何地方定义$logins,也许是$dateLogins???

标签: php arrays symfony phpunit


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 2015-01-01
    相关资源
    最近更新 更多