0

In the example below, loadTargets() correctly returns its assigned stub value when directly called. But when called using self:: inside a parent method it then tries to run the actual, non-stubbed method and fails.

Is there a way to have it work the same as when it is directly called? I thought that a partial mock would do just that.

public function testQueryDbForNewSelection() {
  $adminUtilitiesMock = Mockery
    ::mock('AdminUtilities[loadTargets]');
  $adminUtilitiesMock
    ->shouldReceive('loadTargets')
    ->andReturn(17);

  codecept_debug($adminUtilitiesMock::loadTargets());  // 17

  codecept_debug($adminUtilitiesMock->parentFunc()); // [PHPUnit\Framework\Exception] Undefined index: limit  
}

Also tried: (same error)

public function testQueryDbForNewSelection() {
  $adminUtilitiesMock = Mockery
    ::mock('AdminUtilities')
    ->makePartial();
  $adminUtilitiesMock
    ->shouldReceive('loadTargets')
    ->andReturn(17);

And also:

codecept_debug($adminUtilitiesMock::parentFunc()); // [PHPUnit\Framework\Exception] Undefined index: limit  

Here are the 2 method declarations. My desired behavior is for loadTargets() to be ignored and overwritten by the stubbed value 17 during the invocation inside parentFunc().

 public static function loadTargets() {
    global $wpdb;

    $query = $wpdb->get_results(
      "select * from {$wpdb->prefix}fvc
        limit {$_POST['limit']}
        offset {$_POST['resultMarker']}
    ");

    return $query;
  }


  public static function parentFunc() {
    $data = self::loadTargets();
    codecept_debug($data); // does not print to console, probably due to crashing out on the above line
    codecept_debug('=====$data=====');        
  }
Sean D
  • 3,810
  • 11
  • 45
  • 90

1 Answers1

0

Solved by changing self:: to static::

  public static function parentFunc() {
    $data = static::loadTargets();
    codecept_debug($data); // 17
    return $data;
  }

When to use self over $this?

DO NOT USE self::, use static::

There is another aspect of self:: that is worth mentioning. Annoyingly self:: refers to the scope at the point of definition not at the point of execution.

Sean D
  • 3,810
  • 11
  • 45
  • 90