请原谅我的无知;我还是单元测试领域的新手。
有人能解释为什么......
$this->assertGreaterThan( 2, $result );
..比...更好。
$this->assertTrue( $result > 2 );
..(同样,所有其他特定的断言方法)?
谢谢!
答案 0 :(得分:12)
如果你向妈妈/爸爸/叔叔展示了那些,assertGreaterThan
更加直观。另外,isGreaterThan的失败消息会更好
"1 was not greater than 2"
或
"false was not true"
哪一个更表达?
答案 1 :(得分:3)
实际上,最佳方法提供了更好的可读性和更好的失败消息:使用PHPUnit function-based assertions或Hamcrest 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);
这仍然不理想(因为这些断言不像英语中的句子那样读),但这两种方法都不是更好。