How do I mock get_adjacent_post for testing

I’m trying to mock get_adjacent_post for unit testing but I’m not sure how to mock global function in PHPUnit

    $badCode = $this->getMockBuilder('get_adjacent_post')
        ->setMethods(array('somthing'))
        ->getMock();

Here’s what I got so far which obviously doesn’t work.

And here’s how I use it in production code.

$prev_post = get_adjacent_post( true, '', true, 'topic' );

2 Answers
2

I used WP_Mock for a long time, until I built Brain Monkey to overcome some problems I found working with it.

Using Brain Monkey you can:

use Brain\Monkey\Functions;

Functions::when('get_adjacent_post')->alias(function() {
  // mock here...
});

or

Functions::expect('get_adjacent_post')
  ->atLeast()
  ->once()
  ->with( true, '', true, 'topic' )
  ->andReturnUsing(function( $in_same_term, $excluded_terms, $previous ) {
     // mock here
  });

This latter syntax comes from Mockery.

Brain Monkey, just like WP_Mock, has an API to also mock WordPress hooks.

Leave a Comment