JBZonda / educom-webshop-oop

0 stars 0 forks source link

04: (Optioneel) Unit testing #13

Open JeroenHeemskerk opened 1 year ago

JeroenHeemskerk commented 1 year ago

Dit is een optionele opdracht, overleg met je docent of je deze gaat maken.

 

Example van een interface voor de shopCrud:

<?php

  interface IShopCrud {
  
  public getAllProducts();
  // ...
}

 

Example of a mock of shopCrud:

<?php

class TestShopCrud implements IShopCrud {
  public $sqlQueries = array();
  public $arrayToReturn = array();

  public getAllProducts() {
    array_push($this->$sqlQueries, "getAllProducts");
    return $this->arrayToReturn;
  }
  // ... 
}

Example of a testsuite voor ShopModel:

<?php 

use PHPUnit\Framework\TestCase;

class ShopModelTest extends TestCase
{
    public function testPrepWebShop() {
        // prepare
        $crud= new TestShopCrud(); // <-- create a dummy CRUD 
        $crud->arrayToReturn = array(1 => $this->createTestProduct(1),  // <-- fill the mock object
                                     3 => $this->createTestProduct(3) );

        $pageModel = new PageModel(null, $crud);
        $model = new ShopModel($pageModel, $crud); // <-- This is the object we want to test.

        // test
        $model -> prepWebshop();

        // validate
        $this->assertNotEmpty($model->products);
        $this->assertEqual(1, count($db->sqlQueries));
        $this->assertEqual($db->arrayToReturn, $model->products);
    }

    /**
     * Helper function to create a new test 
     * 
     * @param int $id the id of the product 
     * @return a new Product instance.
     */
    function createTestProduct($id) {
        return new TestProduct($id, "Test".$id, "A Test product", $id * 1.01, "testimage.jpg");
    }

    // other functions of the ProductModel to test all called "test....."

}