#laravel tesing
Explore tagged Tumblr posts
Text
[Laravel][Testing] Display clearly array not equals error messages
Problem
When assertEqual asserting was failed, I can’t not known where the path of properies is not match.
Example: Assume I have many configs(contains inputs and expected result) With bellow test, I will receive the bellow message.
private const CONFIGS = [ [ 'params' => [ 'level' => JlptRank::N4, 'parts_score' => [ JlptCategoryConstant::JLPT_VOCABULARY__VALUE => 50, JlptCategoryConstant::JLPT_READING__VALUE => 50, JlptCategoryConstant::JLPT_LISTENING__VALUE => 50, ] ], 'expect_return_value' => JlptRank::RANK_A ], // ... ];
Test code:
/** @test */ public function it_returns_expect_results() { foreach (self::CONFIGS as $config) { $this->assertEquals( $config['expect_return_value'], JlptRank::calculate_Jlpt_rank(...array_values($config['params'])) ); } }
Test result:
Failed asserting that two strings are equal. Expected :'C' Actual :'D'
It is hard to find where is the *config that happen don’t match.*
Solution
Merge inputs and expected results in to array, and comparsion it.
/** @test */ public function it_returns_expect_results() { foreach (self::CONFIGS as $config) { $this->assertEquals( json_encode($config), json_encode(array_merge($config, ['expect_return_value' => JlptRank::calculate_Jlpt_rank(...array_values($config['params']))])) ); } }
Test result will be:
Failed asserting that two strings are equal. Expected :'{"params":{"level":4,"parts_score":{"91":10,"93":60,"94":10}},"expect_return_value":"C"}' Actual :'{"params":{"level":4,"parts_score":{"91":10,"93":60,"94":10}},"expect_return_value":"D"}'
Now you can easily see which properties don’t match.
0 notes