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

Added an example of using Mockery to mock WordPress objects #61

Merged
merged 2 commits into from
Sep 23, 2016
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,45 @@ public function test_filter_content() {
}
```

### Mocking WordPress objects

Mocking calls to `wpdb`, `WP_Query`, etc. can be done using the [mockery](https://github.com/padraic/mockery) framework. While this isn't part of WP Mock itself, complex code will often need these objects and this framework will let you incorporate those into your tests. Installation can be done via composer.

```
composer require --dev mockery/mockery
```
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might be worth noting that WP Mock already requires Mockery, so if they're already using WP Mock, this step is unnecessary.


#### $wpdb example

Let's say we have a function that gets three post IDs from the database.
```
function get_post_ids() {
global $wpdb;
return $wpdb->get_col( "select ID from {$wpdb->posts} LIMIT 3" );
}
```

When we mock the `$wpdb` object, we're not performing an actual database call, only mocking the results. We need to call the `get_col` method with an SQL statement, and return three arbitrary post IDs.

```
use Mockery;

function test_get_post_ids() {
global $wpdb;

$wpdb = Mockery::mock( '\WPDB' );
$wpdb->shouldReceive( 'get_col' )
->once()
->with( "select ID from wp_posts LIMIT 3" )
->andReturn( array( 1, 2, 3 ) );
$wpdb->posts = 'wp_posts';

$post_ids = get_post_ids();

$this->assertEquals( array( 1, 2, 3 ), $post_ids );
}
```

## Credits

* [Eric Mann](/ericmann)
Expand Down