phpwordpressunit-testingphpunitmockery

How to Mock $wpdb->prefix using WP_Mock and Mockery?


🗺️ My Environment

PHP 7.4
WordPress 6.2
WP_Mock 1.0
PHPUnit 9.6.11
Mockery 1.6.6

🖥️ Code: TestCase

use PHPUnit\Framework\TestCase;
use WP_Mock;
use Mockery;

class WPAB_Database_Service_Test extends TestCase
{
  /**
   * @test
   */
  public function migrate()
  {
    // ... some code ...

    $wpdb_mock = Mockery::mock('WPDB');

    $wpdb_mock
      ->allows('get_charset_collate')
      ->withNoArgs()
      ->andReturn('utf16_general_ci');

    $wpdb_mock->prefix = 'wpbb_';

    $result = $database_service->migrate(); // The function I want test

    $this->assertSame($result, 1);
  }
}

🖥️ Code: Row issue of database_service->migrate()

$prefix = $wpdb->prefix;

🚩 Issue and expectation

After running the test and I have the following warning :

PHP Notice: Undefined property: Mockery_1__WPDB::$prefix in ...

And the current test succeeded for unkown reason. May Mockery return empty string by default 🤔 (If someone got the answer)

Does anyone know how to simulate/mock a specific property (static and non-static) with WP_Mock and/or Mockery ?

I need to know the best way to avoid this type of warning. Thank you in advance for your time ❤️


Solution

  • I just miss the line bellow in my test..

    global $wpdb;