skip to Main Content

I have the following 2 models:

<?php
namespace AppModels;

class Product extends Model
{
    //some other property of the Model

    public function productType() {
        return $this->belongsTo( 'AppModelsProductType', 'product_type_id');
    }
    
    public function theComplicatedFunctionBeingTested() {
        //Some calculation with consideration of ProductType
        return $result;
    }
}
<?php
namespace AppModels;

class ProductType extends Model
{
    //some other property of the Model
    public function products() {
        return $this->hasMany( 'AppModelsProduct', 'product_id');
    }
}

Now that I want to write unit test for theComplicatedFunctionBeingTested() in the Product model. I don’t want to mock the model if it is not necessary, so I create real objects of these Model instead in my unit test.

<?php
use IllumniateFoundationTestingTestCase;

use AppModelsProduct;
use AppModelsProductType;

class ProductFunctionTest extends TestCase
{
    private $testProduct, $testProductType;

    private function commonDataSetUp() {
        $this->testProductType = new ProductType;
        $this->testProductType->product_type_id = 1;
        $this->testProductType->name = "publication";

        $this->testProduct = new Product;
        $this->testProduct->name = "testing product";
        //I tried to assign a relation like this, but this is not working
        $this->testProduct->productType = $this->testProductType;
    }

    public function testComplicatedProductFunction() {
        $this->commonDataSetUp();
        $result = $this->testProduct->theComplicatedFunctionBeingTested();
        $this->assertEquals( 'my_expected_result', $result);
    }
}

However, the relation setup is not successful. As $this->testProduct->productType is not set, the default behavior of Laravel code base is to try accessing database, and as no database connection is set for unit test, it throws exception and the test failed.

So, with no database, what should be the correct way to set up the relation?

2

Answers


  1. You should try this code

    $this->testProduct->setRelation("productType", $this->testProductType);
    

    setRelation is documented in Laravel’s API here

    Login or Signup to reply.
  2. As in the comments, and still meself believe that you should use factories but if you don’t want to use factories then I think this might help you.
    You can create your instances of the models without saving them to database by the make command like below,

    $this->testProductType = ProductType::make([
       // product type model columns
    ]);
    
    $this->testProduct = Product::make([
        // product model Columns
    ]);
    

    and then associate the ProductType with the Product.

    $this->testProduct->productType()->associate($this->testProductType);
    

    I hope this may solve your problem.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search