iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 8
0
自我挑戰組

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

Day08: 替購物車增加功能

今天就先替 Cart 加入 remove 的功能吧

// tests/CartTest.php

<?php

namespace Recca0120\Cart\Tests;

use Recca0120\Cart\Cart;
use Recca0120\Cart\Item;
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());
    }

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

        $cart->remove($item1);

        $this->assertEquals([$item2], $cart->items());
    }
    

    private function createItem($name, $price, $qty)
    {
        return new Item([
            'name' => $name,
            'price' => $price,
            'quantity' => $qty,
        ]);
    }
}
<?php

namespace Recca0120\Cart;

class Cart
{
    private $items = [];

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

        return $this;
    }

    public function remove($item)
    {
        $this->items = array_values(array_filter($this->items, function($o) use ($item) {
            return $o !== $item;
        }));
    }

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

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

上一篇
Day07: 持續優化商品物件2
下一篇
Day09: 增加存檔機制
系列文
單元測試開發購物車功能12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言