How to Unit Test Entity Reference Field Value I have been tasked with writing a Unit Test for a method where I pass in a Node object, modify an Entity Reference field value, and then return a Node object.

Since this is a Unit test, I am unsure as to how to write an assertion.

Note: just included relevant code.

class ClassIAmTesting {
    public function populateSymbols(Node $node) {

      $node-&gt;field_symbols-&gt;appendItem(['target_id' =&gt; $symbol_id]);
      return $node;
    }
}


I have created a mock for the Entity Reference Field:

$entityReferenceMock = $this-&gt;getMockBuilder(EntityReferenceFieldItemList::class)
      -&gt;disableOriginalConstructor()
      -&gt;setMethods(['appendItem'])
      -&gt;getMock();


I have also created a mock of the Node Object

$nodeMock = $this-&gt;getMockBuilder(Node::class)
      -&gt;disableOriginalConstructor()
      -&gt;getMock();

$nodeMock-&gt;expects($this-&gt;any)
      -&gt;method('__get')
      -&gt;with('field_symbols_in_this_story')
      -&gt;willReturn($entityReferenceMock);


The method returns a Node object but how can I assert that the Entity Reference Field Value has changed?

Edit: The class with more details:

class ClassIAmTesting {
  public function populateSymbols(Node $node) {

    $body = $node-&gt;field_body-&gt;value;

    $dom = Html::load($body);
    $xpath = new \DOMXPath($dom);

    foreach ($xpath-&gt;query('//span[@class="tooltip"]') as $xpathNode) {

      $symbol_id = $xpathNode-&gt;getAttribute('data-symbol');

      $node-&gt;field_symbols-&gt;appendItem(['target_id' =&gt; $symbol_id]);
    }

    return $node;
  }
}
This is a good example of a test that would probably be better suited as a kernel test rather than a unit test since it's dealing with the Field API which can get tricky to mock, and is probably better to test with the real thing.

To test this as a kernel test you need to ensure the following:


Either create your field field_symbols directly in the test's setUp method or place the field config and storage YAML files in a module's config/install directory, and enable that module for the test.


You'll need to also enable the node module, and any other module's that your code depends on



Then, in your test you can execute the custom code and ensure the expected values are set:

public function testFieldSymbols() {
  $node = $this-&gt;createNode();

   // Do this, or retrieve the service if your class is a service.
   $fixture = new ClassIAmTesting();

   $fixture-&gt;populateSymbols($node);

   $this-&gt;assertEquals('expected field value', $node-&gt;field_symbols-&gt;target_id);