Brain-WP / BrainFaker

Uses Faker and Brain Monkey to provide easy generation of fake WordPress objects and related functions
34 stars 9 forks source link

Mock WordPress functions with the same object of the provider #6

Open antonioeatgoat opened 3 years ago

antonioeatgoat commented 3 years ago

At the current moment, a mocked object is returned by the provider, when you call it. However, a new mocked object is generated for each stubbed WordPress function. This doesn't allow to rely on the parameters checking, while testing expectations.

I've fixed it for the User provider only for now, if the solution makes sense I can implement the solution for the other providers as well.

Watch out, this PR also include the commit already present in this other one, otherwise I'd not be able to run tests.

This is the code with which you can reproduce the problem:

<?php

use Brain\Monkey;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use PHPUnit\Framework\TestCase as FrameworkTestCase;

class UserParser {
    public function parse(\WP_User $wpUser): string {
        return 'pointless-value';
    }
}

class PostAuthorFetcher {

    /**
     * @var UserParser
     */
    private $userParser;

    public function __construct(UserParser $userParser) {

        $this->userParser = $userParser;
    }

    public function fetchAuthor(\WP_Post $wpPost) {
        return $this->userParser->parse(get_userdata($wpPost->post_author));
    }
}

class FakerTest extends FrameworkTestCase {

    /**
     * @var \Brain\Faker\Providers
     */
    protected $wpFaker;

    /**
     * @return void
     */
    protected function setUp(): void
    {
        parent::setUp();
        Monkey\setUp();

        $this->wpFaker = \Brain\faker()->wp();
    }

    /**
     * @return void
     */
    protected function tearDown(): void
    {
        Monkey\tearDown();
        parent::tearDown();
    }

    public function testFakerStub()
    {
        $mockPost = $this->wpFaker->post(['post_author' => 10]);

        $mockUser = $this->wpFaker->user(['ID' => 10]);

        $mockUserParser = \Mockery::mock(UserParser::class);
        $mockUserParser->expects('parse')
            ->with($mockUser)
            ->andReturn('pointless-value');

        $postAuthorFetcher = new PostAuthorFetcher($mockUserParser);

        $postAuthorFetcher->fetchAuthor($mockPost);
    }
}