Question

I'm trying to unit test a controller where I have $this->library->client->changeLog->create() and I'm wondering if I need to mock each of these properties or if I can just somehow deep mock $this->library so I don't have to have a long chain of objects being mocked and have to worry about their constructor parameters as well. I'm trying to mock a chain right now and it's very ugly and not working very well.

I also tried $this->library->shouldReceive('client->changeLog->create')->once()->andReturn(true); but it leads to a "trying to get property of a non-object.

Is there a simple way to test the output the output of a method that's a few properties deep?

Was it helpful?

Solution

In theory the return result of each of the changed method calls would return $this so you would need to create a mock object and return it on each of the method calls. Here is an example of doing that on stack overflow.

Mock objects which support chaining methods

Code like this can often be seen as a code smell which you can read more about here on this stack overflow post.

"Message Chains" vs "Middle Man"

As you are testing a controller and Im guessing an action within that controller you could perhaps test the output of the controller action. This means the code would all execute and you would test the result of the controller action.

You could then potentially refactor the code so that you don't have the chained method call which would make it easier to mock and test.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top