写一个类和方法,同时写好测试用例,重构的时候始终包成测试用例不被修改
重构的第一步必须有足够的测试来覆盖你所有的代码。这样才能保证你修改的代码不能产生和你原来代码不同的结果。顺便提一下,除非你改变了需求(你代码期望的结果)或者在测试实例中发现了错误,你的测试代码是是不能改变的。
下面是一个测试CartLine和Cart的例子,它在重构的过程中是不会改变的。
<?phpheader("Content-type: text/html; charset=utf-8");
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
require_once 'simpletest/unit_tester.php';
require_once 'simpletest/reporter.php';
// PHP5
class CartLine {
public $price = 0;
public $qty = 0;
/**
* 单行合计
* @return type
*/
public function total() {
return $this->price * $this->qty;
}
}
//
//class Cart {
//
// protected $lines = array();
//
// public function addLine($line) {
//
// $this->lines[] = $line;
// }
//
// public function calcTotal() {
//
// $total = 0;
//
// foreach ($this->lines as $line) {
//
// $total += $this->lineTotal($line);
// }
//
// $total += $this->calcSalesTax($total);
//
// return $total;
// }
//
//
// protected function calcSalesTax($amount) {
//
// return $amount * 0.07;
// }
//
//}
class Cart {
protected $lines = array();
public function addLine($line) {
$this->lines[] = $line;
}
public function calcTotal() {
$total = 0;
foreach ($this->lines as $line) {
$total += $line->total();
}
$total += $this->calcSalesTax($total);
return $total;
}
protected function calcSalesTax($amount) {
return $amount * 0.07;
}
}
class TestingTestCase extends UnitTestCase {
function TestingTestCase($name = '') {
//$this->TestSalesTax();
echo $name;
}
function TestCart() {
$line1 = new CartLine;
$line1->price = 12;
$line1->qty = 2;
$line2 = new CartLine;
$line2->price = 7.5;
$line2->qty = 3;
$line3 = new CartLine;
$line3->price = 8.25;
$line3->qty = 1;
$cart = new Cart;
$cart->addLine($line1);
$cart->addLine($line2);
$cart->addLine($line3);
$this->assertEqual((12 * 2 + 7.5 * 3 + 8.25) * 1.07, $cart->calcTotal());
}
}
$test = new TestingTestCase('购物车测试');
$test->run(new HtmlReporter());