I've created UnitTest based class for my service.

In one of my tested methods from service class I have code like:

if ($node->hasField('field_foo')) {
  $section = $node->field_foo->entity;

I've created mock for Node class and I know how to "emulate" hasField. However, how to mock this line:

$section = $node->field_foo->entity

I'd to set $section to be a Term object (or mock). Is this even possible? Now my test falls with an error:

Trying to get property of non-object

but this is clear why. I'm using just mock, not real Node object.

  • Your question is too vague. Can you please post your entire test method and the method you are trying to test? Oct 2, 2016 at 17:46
  • All that I can add is that $section is returned from this method, so that's why line that I wanted to distinct is important
    – Codium
    Oct 2, 2016 at 21:44

1 Answer 1


Yes, magic methods afaik can't be mocked.

You can use get('field_foo')->entity which does exactly the same as __get(), at least in this case. And then make that return a stdClass object with a ->entity property. That's not exactly the same as what really happens, but it will work in the same way for your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.