Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 在PHPUnit中,为什么特定资产优于一般资产?_Unit Testing_Testing_Phpunit - Fatal编程技术网

Unit testing 在PHPUnit中,为什么特定资产优于一般资产?

Unit testing 在PHPUnit中,为什么特定资产优于一般资产?,unit-testing,testing,phpunit,Unit Testing,Testing,Phpunit,请原谅我的无知;我对单元测试领域还是新手 有人能解释一下原因吗 $this->assertGreaterThan(2$result) …比…好 $this->assertTrue($result>2) ..(以及其他所有特定的断言方法) 谢谢 比…好 谁这么说?两者都一样好。这两种情况下的可读性都不同,但都不是特别好。您可以通过一些变量提取进一步改进它: $minimumValue = 2; $this->assertGreaterThan($minimumValue, $result);

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

有人能解释一下原因吗

$this->assertGreaterThan(2$result)

…比…好

$this->assertTrue($result>2)

..(以及其他所有特定的断言方法)

谢谢

比…好

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

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


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

如果你给你的妈妈/爸爸/叔叔看,那么
断言比
直观得多。再加上失败的消息对于isGreaterThan来说会好得多

"1 was not greater than 2"

哪一种更具表现力?

实际上,最好的方法提供更好的可读性和更好的失败消息:使用or

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

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

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


谢谢你,马丁。此外,我还应该补充我的一位朋友提到的内容:“库是可扩展的,因此,如果出于某种原因,您希望所有GreaterThan检查都能做一些特殊的事情,那么只需扩展和定义您自己的例程即可。”Hamcrest看起来相当不错。我一定要认真看看。根据您的经验,Hamcrest是否会影响PHPUnit扩展?Thanks@Spot-我们已经一起使用了两年多,没有任何问题。要让PHPUnit计算执行的断言数量,您需要使用覆盖
runBare
的。如果您已经像我们一样拥有了自己的抽象测试用例,那么添加它就很简单了。
"false was not true"
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
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