public function thisMethod {
$example = $this->methodReturnsObject()->this1->that2->there3->id;
return $example;
}
How would you test thisMethod in PHPUnit?
Obviously I could write an expectation that methodReturnsObject() will return something... but what? That object has properties associated with it, but how would you even mock that value?
How would you test thisMethod in PHPUnit, I'd either:
Such as:
The answer is "You don't". Unit testing should test each class in isolation, what you are trying to do there is not a unit test. As I said in my comment, you are breaking the Law of Demeter, which simply stated says
You have tightly coupled classes there that need re-factoring. I have written the classes first here to illustrate the point, but I usually write the tests first.
Lets start with the end of the chain:-
Now let's set up a unit test for it:-
That class is now tested, so we don't need to test it again. Now let's look at the next one:-
And now the unit test:-
We'll do one last example to further illustrate my point:-
And, again, the unit test:-
Hopefully, you get the idea without me having to go through all the objects in your example.
What I have done is to de-couple the classes from each other. They only have knowledge of the object they depend on, they don't care how that object gets the information requested.
Now the call for id would look something like:-
Which will go up the chain until the id returned is there2::id. You never have to write something like $this->$this1->$this2->there3->id and you can unit test your classes properly.
For more information on unit testing see the PHPUnit manual.
Use rrehbein's method to build the return value from the mock method and create a partial mock of whatever class contains
thisMethod
andmethodReturnsObject
--the class under test. MockmethodReturnsObject
to return the$value
object created.Assuming that class is named
Foo
gives