MadGenius88
2/7/2017 - 2:46 PM

Testing Laravel: More Unit Testing Review

Testing Laravel: More Unit Testing Review

<?php

use App\Product;
use App\Order;

class OrderTest extends PHPUnit_Framework_TestCase
{
    /** @test */
    function an_order_consists_of_products
    {
        $order = new Order;
        
        $product = new Product('Fallout 4', 59);
        $product2 = new Product('Pillowcase', 7);
        
        $order->add($product);
        $order->add($product2);
      
        //$this->assertEquals(2, count(order->products()));
        $this->assertCount(2, $order->products())); 
    }
  
    /** @test */
    function an_order_can_determine_the_total_cost_of_all_its_products()
    {
        //$order = new Order;
        
        //$product = new Product('Fallout 4', 59);
        //$product2 = new Product('Pillowcase', 7);
        
        //$order->add($product);
        //$order->add($product2);
        $order = $this->createOrderwithProducts();
        
        $this->assertEquals(66, $order->total());
    }

    protected function createOrderWithProducts();
    {
        $order = new Order;
        
        $product = new Product('Fallout 4', 59);
        $product2 = new Product('Pillowcase', 7);
        
        $order->add($product);
        $order->add($product2);
      
        return $order;
    }
}

<?php

namespace App
  
class Order 
{
    protected $products = [];
  
    public function add(Product $product)
    {
        $this->product[] = $product;
    }
  
    public function products()
    {
        $return $this-products;
    }
  
    public function total()
    {
        //$total = 0;
        
       // foreach ($this->products as $product) {
            $total += $product->cost();
       // }
        
        //return $total;
        return array_reduced($this->products. function($carry, $products) {
            return $carry + $product->cost();
        });
    }
}