如何在Laravel中分配belongsTo关系而不保存到数据库?

问题描述 投票:0回答:1

我有以下2款:

<?php
namespace App\Models;

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

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

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

现在我想在

theComplicatedFunctionBeingTested()
模型中为
Product
编写单元测试。如果没有必要,我不想模拟模型,因此我在单元测试中创建这些模型的真实对象。

<?php
use Illumniate\Foundation\Testing\TestCase;

use App\Models\Product;
use App\Models\ProductType;

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);
    }
}

但是,关系设置不成功。由于未设置

$this->testProduct->productType
,Laravel 代码库的默认行为是尝试访问数据库,并且由于没有为单元测试设置数据库连接,因此会抛出异常,测试失败。

那么,在没有数据库的情况下,建立关系的正确方法应该是什么?

php laravel unit-testing phpunit
1个回答
0
投票

你应该尝试这个代码

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

setRelation
记录在 Laravel 的 API 这里

© www.soinside.com 2019 - 2024. All rights reserved.