为什么特定断言比PHPUnit中的泛型断言更好?

时间:2012-10-25 18:05:34

标签: unit-testing testing phpunit

请原谅我的无知;我还是单元测试领域的新手。

有人能解释为什么......

$this->assertGreaterThan( 2, $result );

..比...更好。

$this->assertTrue( $result > 2 );

..(同样,所有其他特定的断言方法)?

谢谢!

3 个答案:

答案 0 :(得分:12)

如果你向妈妈/爸爸/叔叔展示了那些,assertGreaterThan更加直观。另外,isGreaterThan的失败消息会更好

"1 was not greater than 2"

"false was not true"

哪一个更表达

答案 1 :(得分:3)

实际上,最佳方法提供了更好的可读性更好的失败消息:使用PHPUnit function-based assertionsHamcrest library

assertThat(count($users), greaterThan(2));

>> Expected: greater than 2
>>      but: was 1

assertThat($users, arrayWithSize(greaterThan(2)));

>> Expected: array with size greater than 2
>>      but: was array with size 1

您可以随时通过向断言方法或Hamcrest的assertThat函数添加字符串作为第一个参数或向PHPUnit的assertThat函数添加第三个参数来提供任何断言的可读错误消息:

self::assertTrue('At least one user found', !empty($users));

>> At least one user found
>> Expected: true
>>      but: false

assertThat('At least one user found', !empty($users), is(true));

>> At least one user found
>> Expected: true
>>      but: false

答案 2 :(得分:0)

  

比...更好。

谁这么说?两者都一样好。两种情况下的可读性都不同,但两者都不是特别好。您可以通过一些变量提取进一步改进它:

$minimumValue = 2;
$this->assertGreaterThan($minimumValue, $result);

$resultGreaterThanMinimumValue = $result > 2;
$this->assertTrue($resultGreaterThanMinimumValue);

这仍然不理想(因为这些断言不像英语中的句子那样读),但这两种方法都不是更好。