【发布时间】:2013-09-26 06:28:25
【问题描述】:
从这个例子中,CoffeeWithCream 的 getBrand() 方法是否不合适或有任何问题?我这样做的原因是避免在任何被调用的地方都写 $coffeeWithCream->$coffee->getBrand()。
特别是,出现的一个关注领域是单元测试。我对单元测试还不够熟悉,不知道这种策略是否会使测试复杂化。
另外,我知道 getBrand() 只是一个简单的访问器方法。如果该方法执行更复杂的任务,答案会改变吗?
Class Coffee {
public $brand;
public $ingredients = array('coffee');
public function getBrand() {
return $this->brand;
}
public function getIngredients() {
return $this->ingredients;
}
}
Class CoffeeWithCream {
public $coffee;
public __construct(Coffee $coffee) {
$this->coffee = $coffee;
}
public function getIngredients() {
$ingredients = $this->coffee->getIngredients();
$ingredients[] = 'cream';
return $ingredients;
}
public function getBrand() {
$this->coffee->getBrand();
}
}
【问题讨论】:
-
我认为单元测试不会那么复杂,因为您能够(并且应该)注入
Coffee的模拟版本并测试在调用时是否调用了方法Coffee::getBrand()CoffeeWithCream::getBrand()。反之,当你测试Coffee::getBrand()时,只测试这个特定方法的行为是否正确,反正你会怎么做。
标签: php unit-testing decorator