Laravel mocking Model / QueryBuilder

178 views Asked by At

I've been playing around with unit tests for a while but I've reached a point that I'm not sure how I can achieve what I want.

I've got a test that involves a JsonResource, and within this JsonResouce I have this sample.

'id' => $this->id,
'name' => $this->name,
'state' => $this->state->name,
'users' => UsersResource::collection($this->users()->limit($userLimit)->get()),
'clients' => ClientsResource::collection($this->clients()->limit($clientLimit)->get()),

My test involves calling this JsonResource, which is related to a model of Group, that contains users and clients alongisde some other attributes. To mock the operation that is being done before calling this JsonResource, I've used a Mock on the repository that wraps my Group class, saying it should return an instance of Group:class. It then comes the time that the jsonresource is called with this Group instance, and I need to mock these attributes, but since clients() and users() are functions, I need to mock those since there is no database access. Here comes Mockery::mock(Group::Class)

$this->groupMock = Mockery::mock(Group::class);
$this->groupMock->shouldReceive('getAttribute')->with('id')->once()->andReturn(1);
$this->groupMock->shouldReceive('getAttribute')->with('state')->once()->(new GroupState(['name' => 'some group name']));
$this->groupMock->shouldReceive('getAttribute')->with('name')->once()->andReturn('something');

I'm wondering how I can make these lines below work. As far as I can tell, it doesn't recognise the order of the method calls or "concatenating" order. Is it achievable? How could I make this work?

$this->groupMock->shouldReceive('clients')->andReturn($this->groupMock)
->shouldReceive('limit')->with(6)->andReturn($this->groupMock)
->shouldReceive('get')->andReturn(collect(factory(User::class, 2)->make()));

$this->groupMock->shouldReceive('users')->andReturn($this->groupMock)
->shouldReceive('limit')->with(8)->andReturn($this->groupMock)
->shouldReceive('get')->andReturn(collect(factory(User::class, 6)->make()))
0

There are 0 answers