下面一个测试代码就是测试 PropertyInfo 类的:
function testPropertyInfo() { $list = array(‘type’,’price’,’color’,’rent’); $this->assertIsA( $testprop = new PropertyInfo($list), ‘PropertyInfo’); foreach($list as $prop) { $this->assertEqual($prop, $testprop->$prop); } }
这个测试证明:每个PropertyInfo类都有四个公共属性,而且具有按精确次序排列的叁数。 但是因为实例中 RailRoad 和 Utility 类并不需要颜色或者租用数据, 所以我们需要测试PropertyInfo 也能引入少量的参数而实例化为RailRoad 和 Utility 类对象:
function testPropertyInfoMissingColorRent() { $list = array(‘type’,’price’); $this->assertIsA( $testprop = new PropertyInfo($list), ‘PropertyInfo’); $this->assertNoErrors(); foreach($list as $prop) { $this->assertEqual($prop, $testprop->$prop); } $this->assertNull($testprop->color); $this->assertNull($testprop->rent); }
注:assertNoErrors() assertNoErrors() 方法的作用是:证实没有PHP 错误发生。如果有错误, 将不通过测试。 assertNull() assertNull()方法的作用是:测试第一个参数是否为空。 如果第一个参数不为空, 将不通过测试。像大多数其他测试方法一样,, 你可以选择是否使用第二个叁数定义失败信息。
为了满足前面的测试,PropertyInfo 类定义为:
class PropertyInfo { const TYPE_KEY = 0; const PRICE_KEY = 1; const COLOR_KEY = 2; const RENT_KEY = 3; public $type; public $price; public $color; public $rent; public function __construct($props) { $this->type = $this->propValue($props, ‘type’, self::TYPE_KEY); $this->price = $this->propValue($props, ‘price’, self::PRICE_KEY); $this->color = $this->propValue($props, ‘color’, self::COLOR_KEY); $this->rent = $this->propValue($props, ‘rent’, self::RENT_KEY); } protected function propValue($props, $prop, $key) { if (array_key_exists($key, $props)) { return $this->$prop = $props[$key]; } } }
现在PropertyInfo 类可以构造各种不同的Property参数了。同时Assessor类可以提供数据来建立正确的PropertyInfo对象。 现在以Assessor->$prop_info数组提供的数据为基础,新建一个实例化 PropertyInfo 的类。 这样的代码可以是:
class Assessor { protected $game; public function setGame($game) { $this->game = $game; } public function getProperty($name) { $prop_info = new PropertyInfo($this->prop_info[$name]); switch($prop_info->type) { case ‘Street’: $prop = new Street($this->game, $name, $prop_info->price); $prop->color = $prop_info->color; $prop->setRent($prop_info->rent); return $prop; case ‘RailRoad’: return new RailRoad($this->game, $name, $prop_info->price); break; case ‘Utility’: return new Utility($this->game, $name, $prop_info->price); break; default: //should not be able to get here } } protected $prop_info = array(/* ... */); }
这段代码实现了上述功能, 但却非常脆弱。如果代入的值是$this->prop_info数组中没有的值,结果会怎样呢?因为 PropertyInfo 已经被实例化并被加入到Assessor代码中, 没有有效的方法测试被产生的对象。比较好的解决就是:产生一个工厂方法使 PropertyInfo 对象更容易建立。 因此, 下一步将是写一个测试来实现Assessor类中的PropertyInfo方法。
但是,有一个问题: 这个方法不应该是Assessor类的公共接口(API)的一个部份。它能被测试吗?
这里有两个方法, 可以探究任何要求的合理数量的测试。简单的说, 你可以运行黑匣子测试或白匣子测试。
注:黑匣子测试(Black Box Testing) 黑匣子测试就是:把被测试的对象当成" 黑匣子 " ,我们只知道它提供的应用接口(API),但不知道其到底执行了什么。它主要测试对象公共方法的输入和输出。 白匣子测试(White Box Testing) 白匣子测试和黑匣子测试恰恰相反, 它假定知道测试对象中的所有代码信息。这种形式的测试是为了完善代码和减少错误。 关于白匣子测试的详细说明请见:http:// c 2.com/cgi/wiki?WhiteBoxTesting 。
出处:
责任编辑:bluehearts
上一页 php设计模式介绍之工厂模式 [6] 下一页 php设计模式介绍之工厂模式 [8]
◎进入论坛网络编程版块参加讨论
|