Make WordPress Core


Ignore:
Timestamp:
10/15/2015 04:43:37 AM (9 years ago)
Author:
wonderboymusic
Message:

Unit Tests: implement setUpBeforeClass() and tearDownAfterClass() on WP_UnitTestCase. Use late static binding (plus a gross fallback for PHP 5.2) to check if wpSetUpBeforeClass() or wpTearDownAfterClass() exist on the called class, and then call it and pass a static WP_UnitTest_Factory instance via Dependency Injection, if it exists.

This makes it way easier to add fixtures, and tear them down, without needing to instantiate WP_UnitTest_Factory in every class - removes the need to call commit_transaction() in each individual class.

See #30017, #33968.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tests/phpunit/includes/testcase.php

    r35136 r35186  
    1919     */
    2020    protected $factory;
     21
     22    protected static $static_factory;
     23
     24    public static function get_called_class() {
     25        if ( function_exists( 'get_called_class' ) ) {
     26            return get_called_class();
     27        }
     28
     29        // PHP 5.2 only
     30        $backtrace = debug_backtrace();
     31        // [0] WP_UnitTestCase::get_called_class()
     32        // [1] WP_UnitTestCase::setUpBeforeClass()
     33        if ( 'call_user_func' ===  $backtrace[2]['function'] ) {
     34            return $backtrace[2]['args'][0][0];
     35        }
     36        return $backtrace[2]['class'];
     37    }
     38
     39    public static function setUpBeforeClass() {
     40        parent::setUpBeforeClass();
     41
     42        $c = self::get_called_class();
     43        if ( ! method_exists( $c, 'wpSetUpBeforeClass' ) ) {
     44            return;
     45        }
     46
     47        if ( ! self::$static_factory ) {
     48            self::$static_factory = new WP_UnitTest_Factory();
     49        }
     50
     51        call_user_func( array( $c, 'wpSetUpBeforeClass' ), self::$static_factory );
     52
     53        self::commit_transaction();
     54    }
     55
     56    public static function tearDownAfterClass() {
     57        parent::tearDownAfterClass();
     58
     59        $c = self::get_called_class();
     60        if ( ! method_exists( $c, 'wpTearDownAfterClass' ) ) {
     61            return;
     62        }
     63
     64        call_user_func( array( $c, 'wpTearDownAfterClass' ) );
     65
     66        self::commit_transaction();
     67    }
    2168
    2269    function setUp() {
Note: See TracChangeset for help on using the changeset viewer.