Skip to content

Expect a stub doesn't work #150

@MatzeKitt

Description

@MatzeKitt

I use a stub to make get_post available, which returns a mock of WP_Post:

        $post = Mockery::mock(\WP_Post::class);
        $post->ID = 1;
        $post->post_content = '<!-- wp:heading {"level":1} -->
<h1 class="wp-block-heading">Heading 1</h1>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>This is content.</p>
<!-- /wp:paragraph -->';
        $post->post_status = 'publish';
        $post->post_type = 'page';
        stubs(
            [
                'get_post' => $post,
                'get_queried_object_id' => 1,
            ]
        );

This is my test:

expect('get_post')->once();
$this->assertEquals(true, My_Class::get_instance()->has_content('This is content.'));
$this->assertEquals(true, My_Class::get_instance()->has_content('This is content.'));

My_Class:

<?php
final class My_Class {
	/**
	 * @var		array A list of available content
	 */
	private array $has_content = [];
	
	public function has_content( string $content ): bool {
		// already searched for this content, return stored value
		if ( isset( $this->has_content[ $content ] ) ) {
			return $this->has_content[ $content ];
		}
		
		$post = \get_post( \get_queried_object_id() );
		
		if ( ! $post instanceof WP_Post ) {
			$this->has_content[ $content ] = false;
			
			return false;
		}
		
		// search in post content
		if ( \strpos( $post->post_content, $content ) !== false ) {
			$this->has_content[ $content ] = true;
			
			return true;
		}
		
		return false;
	}
}

Since I want to test whether I already searched for the content, which would result in an early return for the second run, I thought expect('get_post')->once(); would be correct. However, the error message implies it is not:

[Mockery\Exception\InvalidCountException] Method get_post(<Any Arguments>) from Mockery_1 should be called
 exactly 1 times but called 0 times.  

Am I doing wrong here?

As a workaround, I currently test for expect('strpos')->once();, which works when allowing redefining internals for strpos in the patchwork.json.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions