![](/img/trans.png)
[英]phpunit fails asserting that two arrays are equal, but shows no difference
[英]Failed asserting two arrays are equal but shows that the arrays are the same with no difference?
我正在嘗試通過一項涉及運行查詢的測試,該查詢返回一系列登錄以測試測試中兩個數組是否相等。
過去,我嘗試過更改查詢的格式以使測試通過以及編輯數組,最終使其等於兩個數組。 不幸的是,測試仍然沒有通過。
執行查詢以獲取一系列登錄日期的函數:
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']);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.