iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 3
0
自我挑戰組

單元測試開發購物車功能系列 第 3

Day 03: 第一次重構

撰寫到這邊就可以進行重構了,
今天一看程式碼發現 Cart 取得所有商品內容稱為 all 覺得不是很合理,
所以想把 method 從 all 修改為 items
並且測試 code 內有重覆的羅輯在裡面
為了接下來的開發更容易修改,所以也得把測試進行一次重構

修改後程式碼如下

// tests/CartTest.php

namespace Recca0120\Cart\Tests;

use Recca0120\Cart\Cart;
use PHPUnit\Framework\TestCase;

class CartTest extends TestCase
{
    /** @test */
    public function 將商品加入購物車並驗證商品有名稱單價數量()
    {
        $item = $this->createItem('商品01', 100, 1);

        $cart = new Cart();
        $cart->put($item);

        $this->assertArraySubset([$item], $cart->items());
    }

    /** @test */
    public function 加總()
    {
        $cart = new Cart();
        $cart->put($this->createItem('商品01', 100, 2));
        $cart->put($this->createItem('商品02', 200, 1));

        $this->assertEquals(400, $cart->total());
    }

    private function createItem($name, $price, $qty)
    {
        return compact('name', 'price', 'qty');
    }
}
// Cart.php

namespace Recca0120\Cart;

class Cart
{
    private $items = [];

    public function put($item)
    {
        array_push($this->items, $item);

        return $this;
    }

    public function items()
    {
        return $this->items;
    }

    public function total()
    {
        return array_sum(array_map(function ($item) {
            return $item['price'] * $item['qty'];
        }, $this->items));
    }
}

這樣看起來是不是比上一個版本舒服多了,
雖然是小改版,看起來就像今天是來騙文章的
但這個修改對未來可是有大大的影響
就讓我們接著看下去吧

先預告一下明天要實作的部份
從程式碼來看『商品』目前是用 Array 來進行紀錄
但希望商品能以物件的方式來呈現
希望『商品』本身這個物件能有更的功能
所以明天就會先來進行『商品』的重構
並適當的調整程式碼
敬請期待囉


上一篇
Day 02: 撰寫購物車程式
下一篇
Day04: 將商品重構為物件
系列文
單元測試開發購物車功能12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言