[wp-trac] [WordPress Trac] #59482: Tests: Introduce Reflection API helper methods.

WordPress Trac noreply at wordpress.org
Thu Sep 28 02:39:32 UTC 2023


#59482: Tests: Introduce Reflection API helper methods.
------------------------------+---------------------
 Reporter:  costdev           |       Owner:  (none)
     Type:  enhancement       |      Status:  new
 Priority:  normal            |   Milestone:  6.4
Component:  Build/Test Tools  |     Version:
 Severity:  normal            |  Resolution:
 Keywords:  has-patch         |     Focuses:
------------------------------+---------------------

Comment (by costdev):

 == Example

 Ensure that a private property is set when a private method is called.

 What this would normally look like:
 {{{#!php
 <?php
 public function test_should_set_queries() {
     // Reflect the property.
     $reflected_property = new ReflectionProperty( self::$instance,
 'queries' );

     // Make the property accessible.
     $reflected_property->setAccessible( true );

     // Backup the property's value.
     $queries_backup = $reflected_property->getValue( self::$instance );

     // Reflect the method.
     $reflected_method = new ReflectionMethod( self::$instance,
 'do_something' );

     // Make the method accessible.
     $reflected_method->setAccessible( true );

     // Invoke the method.
     $reflected_method->invoke( self::$instance );

     // Make the method inaccessible.
     $reflected_method->setAccessible( false );

     // Get the property's value.
     $actual = $reflected_property->getValue( self::$instance, 'queries' );

     // Restore the property's value.
     $reflected_property->setValue( self::$instance, $queries_backup );

     // Make the property inaccessible.
     $reflected_property->setAccessible( false );

     $this->assertSame( 'expected_queries', $actual );
 }
 }}}

 What this could look like:
 {{{#!php
 <?php

 public function test_should_set_queries() {
     // Reflect the property and backup its value.
     $queries_backup = $this->reflect_and_get_value( self::$instance,
 'queries' );

     // Reflect and invoke the method.
     $this->reflect_and_invoke( self::$instance, 'do_something' );

     // Reflect and get the property's value.
     $actual = $this->reflect_and_get_value( self::$instance, 'queries' );

     // Reflect and restore the property's value.
     $this->reflect_and_set_value( self::$instance, 'queries',
 $queries_backup );

     $this->assertSame( 'expected_queries', $actual );
 }
 }}}

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/59482#comment:1>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list