P
P
part_os2019-01-06 01:52:31
PHPUnit
part_os, 2019-01-06 01:52:31

How to Mock PHPUnit related models in Laravel?

Hello everyone, tell me how to lock the linked model?

class Test1 extends Model
{
public function type_status()
{
     return $this->belongsTo('App\Types', 'type_id');
}
}

class Types extends Model
{
}

write a test:
public function testGetTable()
    {
        $test1= $this->createMock(Test1::class);
        $test1->type_id = 1;

        $types = $this->createMock(Types::class);
        $types->id = 1;
        $types->type = 'Type1';
        $types->reduction = 'T1';

        $test1->attach($types);
     }

The test shows that type_status => null
in the method that I'm testing is called: $test1->type_status ->reduction
tried the same:
$test1->method('type_status')->willReturn('T1');

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
part_os, 2019-01-08
@part_os

In general, my decision was:
1. installing codeception
2. wrapping the public function type_status () method in:

public function getTypes()
    {
       return $this->type_status;
    }

3. replacement in code with this method
4. use in tests
Stub::make(Test1::class,
[
'getTypes' => function(){}
]);

as a result, I got tests and an explicit method call in the code.

A
Alexey Ukolov, 2019-01-06
@alexey-m-ukolov

$test1->type_status()->attach($types);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question