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

WordPress Trac noreply at wordpress.org
Thu Sep 28 02:39:22 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            |   Keywords:  has-patch
  Focuses:                    |
------------------------------+-----------------------
 In unit tests, the Reflection API is often used to get or set a `private`
 or `protected` property's value, or to invoke a `private` or `protected`
 method.

 To do so, the `Reflection<Method|Property>::setAccessible()` method must
 be called with `true` before use, then should be called again with `false`
 afterwards. There are quite a lot of instances in the test suite where the
 Reflection API is used, and for a decent number of these, accessibility is
 not reset.

 For brevity, much like `assertSameSets()`, and to ensure that
 accessibility is always reset, this ticket aims to introduce new methods
 to the `WP_UnitTestCase_Base` class:

 `::reflect_and_invoke( object $obj, string $method, mixed ...$args ) :
 mixed`
   - Reflects a `private` or `protected` method and invokes it.
   - Returns the method's return value.
 `::reflect_and_get_value( object $obj, string $property ) : mixed`
   - Reflects a `private` or `protected` property and gets its value.
   - Returns the property's value.
 `::reflect_and_set_value() : void`
   - Reflects a `private` or `protected` property and sets its value.

 While this means the creation of new `Reflection<Method|Property>` objects
 and two calls to `::setAccessible()` for each, I think that this is
 worthwhile as it helps us have a more robust test suite, with less code to
 write in test methods. Plus, we could also explore possible caching in
 future.

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


More information about the wp-trac mailing list