php学习第二天:代码重构

     写一个类和方法,同时写好测试用例,重构的时候始终包成测试用例不被修改

重构的第一步必须有足够的测试来覆盖你所有的代码。这样才能保证你修改的代码不能产生和你原来代码不同的结果。顺便提一下,除非你改变了需求(你代码期望的结果)或者在测试实例中发现了错误,你的测试代码是是不能改变的。

      下面是一个测试CartLine和Cart的例子,它在重构的过程中是不会改变的。

<?php

header("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());


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值