0

I'm writing unit tests (not integration) for a lib I'm working on. There, we created some WP-CLI commands that I'd like to test. Most of them are just renaming things, copying and pasting things over from the lib to the project.

And when something is successful or not a WP_CLI::success() or similar methods are used to output the message to the user (log, warning or error).

So what I'd like to do is just to output the contents of those methods so that I can test if the desired output happened.

Using Mockery I tried doing the following

// Mock certain WPCLI methods.
$wpCliMock = \Mockery::mock('alias:WP_CLI');
$wpCliMock
    ->shouldReceive('success')
    ->andReturnArg(0);

But it seems that it isn't working because my tests throw Call to a member function fetchMock() on null and the error points to the success method.

The tests are located here. I'm using Pest as my testing framework.

1 Answer 1

0

So I am using PEST as my testing framework, and if I just define my mocks in the helpers, they won't be called correctly, because the WPCLI will probably be autoloaded after that on each test. So I added

beforeEach(function () {
    $wpCliMock = \Mockery::mock('alias:WP_CLI');

    $wpCliMock
        ->shouldReceive('success')
        ->andReturnArg(0);

    $wpCliMock
        ->shouldReceive('error')
        ->andReturnArg(0);
});

Inside my tests, and now everything is passing correctly.

EDIT

Since I'm not actually using real WP_CLI, and the success or error like commands will usually output things to STDERR or STDOUT. That means your return won't actually return anything (andReturnArg(0) part).

So you can actually try to see what arguments are passed and set these to the temp env var that you can then test against. For instance:

    $wpCliMock = \Mockery::mock('alias:WP_CLI');

    $wpCliMock
        ->shouldReceive('error')
        ->andReturnUsing(function ($message) {
            putenv("ERROR_HAPPENED={$message}");
        });

Now if inside your code you have

\WP_CLI::error('Error has happened!');

you'll be able to test this in your test using

$this->assertSame('Error has happened!', getenv('ERROR_HAPPENED'));

Just make sure you clean up the temp env var not to pollute other tests.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.