# create a laravel project
composer create-project laravel/laravel app
# create alias to quick access phpunit
alias phpunit=vendor/bin/phpunit
# create unit test folder
mkdir tests/unit
# create a unit test for Product model
php artisan make:test unit/ProductTest
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class ProductTest extends TestCase
{
    protected $product;
    public function setUp()
    {
        $this->product = new Product('Fallout 4', 59);
    }
    /** @test */
    public function a_product_has_a_name()
    {
        $this->assertEquals('Fallout 4', $this->product->name());
    }
    /** @test */
    public function a_product_has_a_price()
    {
        $this->assertEquals(59, $this->product->price());
    }
}
 | 
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Product extends Model
{
    protected $name;
    protected $price;
    public function __construct($name, $price)
    {
        $this->name = $name;
        $this->price = $price;
    }
    public function name()
    {
    	return $this->name;
    }
    public function price()
    {
        return $this->price;
    }
}
 | 
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | class OrderTest extends TestCase
{
    /** @test */
    public function an_order_consists_of_products()
    {
        $order = $this->createOrder();
        $this->assertEquals(2, count($order->products()));
    }
    /** @test */
    public function an_order_can_determine_the_total_cost_of_all_its_products()
    {
        $order = $this->createOrder();
        $this->assertEquals(66, $order->total());
    }
    protected function createOrder()
    {
        $order = new Order;
        $product = new Product('Fallout 4', 59);
        $product2 = new Product('Pillowcase', 7);
        $order->add($product);
        $order->add($product2);
        return $order;
    }
}
 | 
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Order extends Model
{
    protected $products = [];
    public function add(Product $product)
    {
        $this->products[] = $product;
    }
    public function products()
    {
        return $this->products;
    }
    public function total()
    {
        return array_reduce($this->products, function($carry, $product) {
            return $carry + $product->price();
        });
    }
}
 | 
 
No comments:
Post a Comment