How to write PHPUnit test for any function that has external dependencies? I have 1 function that returns value of any field of particular content type. For this I need to load my current user and a node from where I will retrieve value.

But loading user calls User class and when I run the test, it says undefined method - user_load.

My function is:

public static function get_ctype_field_value($field) {

    $user = user_load(\Drupal::currentUser()-&gt;id());
    $ulm = get_type_id($user); // another function in some class, return value 445
    $local_market = \Drupal\node\Entity\Node::load($ulm);
    $llf = '';
    if ($local_market) {
      // Get the field value from the LM.
      if ($local_market-&gt;hasField($field)) {
        $localmarket_field = $local_market-&gt;$field-&gt;value;
      }
    }
    return $localmarket_field;
  }


AND my test function is:

class MyControllerTest extends UnitTestCase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['node'];

  /**
   * Users to use during this test.
   *
   * @var array
   */
  protected $users = [];

  /**
   * Nodes to use during this test.
   *
   * @var array
   */
  protected $nodes = [];

  protected function setUp() {
    parent::setUp();
    $container = new ContainerBuilder();
    $methods = get_class_methods('\Drupal\Core\Entity\EntityManager');

    $entityManager = $this-&gt;getMockBuilder('\Drupal\Core\Entity\EntityManager')
  -&gt;disableOriginalConstructor()
  -&gt;getMock();

  }

  public function test_get_ctype_field_value() {
    $originalString = 'field_vat';
    $expectedResult = '10.00';
    $econtroller = new myController(); //controller where function resides
    $this-&gt;account-&gt;expects($this-&gt;once())
      -&gt;method('user_load');
    $this-&gt;users[] = $this-&gt;account-&gt;load(1);
    $result = $econtroller-&gt;get_ctype_field_value($originalString);
    $this-&gt;assertEquals($expectedResult, $result);
  }
}


Please suggest any way to write PHPUnit test for this function.

The error I'm getting is:


  Error: Call to a member function load() on null
The code is dependent on Drupal's service container existing, and thus a container needs to be instantiated and used. This is possible in PHPUnit tests using the \Drupal::setContainer() method, and creating a container object.

use Drupal\Core\DependencyInjection\ContainerBuilder;

protected function setUp() {
  parent::setUp();

  $this-&gt;account = $this
    -&gt;getMockBuilder('Drupal\user\Entity\User')
    -&gt;disableOriginalConstructor()
    -&gt;getMock();

  // Create a new container object.
  $container = new ContainerBuilder();

  // Add a service into it.
  $container-&gt;set('current_user', $this-&gt;account);

  // Let Drupal use your mock container.
  \Drupal::setContainer($container);
}