您應爲每個應用程序中的每個方法/函數的每一個可能的路徑中的一個測試用例。在您的例子中,你有第一個條件,兩種可能的情況下,當$ foo是不同的3個不同至5,當$ foo是等於3或5。因此,首先應該創建兩個測試用例:
<?php
class YourClassTest extends PHPUnit_Framework_Testcase
{
public function test_when_foo_is_different_to_three_or_five()
{
$this->assertEquals('expected result when foo is different from 3 or 5', myfunction(1));
}
public function test_when_foo_is_equal_to_three_or_five()
{
$expected = 'expected result when foo=3 or foo=5';
$this->assertEquals($expected, myfunction(3));
$this->assertEquals($expected, myfunction(5));
}
}
現在您應該對條件和排列的其餘部分也做同樣的事情。但是,通過意識到myfunction()方法做了太多事情並且很難進行測試和理解,因此您發現了一個很好的發現,因此您應該將所有條件移至不同的方法並單獨進行測試,然後使用myfunciton()在如果你絕對需要,可以選擇你想要的訂單考慮以下方法:
function myFunction($foo, $bar, $baz)
{
doSomethingWithFoo($foo);
doSomethingWithBar($bar);
doSomethingWithBaz($baz);
}
function doSomethingWithFoo($foo)
{
if (($foo != 3) AND ($foo != 5)) {
// something
}
}
function doSomethingWithBar($bar)
{
if (($bar < 1) OR ($bar > 10)) {
// something
}
}
function doSomethingWithBaz($baz)
{
if ((strlen($baz) === 0) OR (strlen($baz) > 10)) {
// something
}
}
測試將幫助你很多與這種重構。希望這可以幫助你更清楚地說明。