Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AnyInstance matcher for expectHookAdded #160

Closed
BrianHenryIE opened this issue Jan 30, 2021 · 0 comments · Fixed by #161
Closed

AnyInstance matcher for expectHookAdded #160

BrianHenryIE opened this issue Jan 30, 2021 · 0 comments · Fixed by #161
Assignees
Milestone

Comments

@BrianHenryIE
Copy link
Contributor

BrianHenryIE commented Jan 30, 2021

Problem:

Currently WP_Mock needs a reference to an object instance for expectHookAdded to work. A common pattern where this is a problem is where the actions and filters are added during object construction.

class Problem {
	public function __construct() {
		add_filter( 'init', array( $this, 'on_init' ) );
	}
	public function on_init(){	
	}
}
class Similarly {
	public function on_init(){
	}
}
function go() {
	$similarly = new Similarly();
	add_filter( 'init', array( $similarly, 'on_init' ) );
}
go();

The problem is described in #8, #80, #93, #127, #143.

Solution:

Add a matcher like WP_Mock::fuzzyObject()AnyInstance().

Allowing:

\WP_Mock::expectActionAdded( 'init', array( new AnyInstance( Problem::class ), 'on_init' ) );

This is basically the solution proposed in #12 .

I have this working in my own fork: Add AnyInstance matcher.

And can be tested with:

{
    "require-dev": {
        "10up/wp_mock": "0.4.2",
        "cweagans/composer-patches": "*"
    },
    "extra": {
        "patches": {
            "10up/wp_mock": {
                "Add AnyObject matcher": "https://github.com/BrianHenryIE/wp_mock/pull/1.patch"
            }
        }
    }
}

Describe alternatives you've considered

The general advice has been to separate object construction and adding hooks. This is fine, but the solution to this is easy and is coherent with WP_Mock.

I tried adding the functionality into FuzzyObject but became uncertain of side-effects. It may be possible, and preferable. The current code is a straightforward proof of concept – I expect suggestions and alterations before any PR.

@jeffpaul jeffpaul added this to the 0.4.3 milestone Jul 7, 2021
@jeffpaul jeffpaul linked a pull request Jul 7, 2021 that will close this issue
6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants