|
| 1 | +--- |
| 2 | +layout: doc |
| 3 | +title: Plugin Unit Tests |
| 4 | +description: How to set up and run PHPUnit tests for a WordPress plugin. |
| 5 | +category: Guides |
| 6 | +--- |
| 7 | + |
| 8 | +This guide will demonstrate how to: |
| 9 | + |
| 10 | +* set up unit tests for an existing plugin, using WP-CLI |
| 11 | +* run the tests locally |
| 12 | + |
| 13 | +We're going to assume that you already have a plugin called `my-plugin`. |
| 14 | + |
| 15 | +So, let's get started: |
| 16 | + |
| 17 | +1) [Install PHPUnit](https://github.com/sebastianbergmann/phpunit#installation) (4.8.x required, 5.x not supported). |
| 18 | + |
| 19 | +2) Generate the plugin test files: |
| 20 | + |
| 21 | + wp scaffold plugin-tests my-plugin |
| 22 | + |
| 23 | +This command will generate all the files needed for running tests, including a `.travis.yml` file. If you host your plugin on Github and enable [Travis CI](http://about.travis-ci.org), the tests will be run automatically after every commit you make to the plugin. |
| 24 | + |
| 25 | +3) Initialize the testing environment locally: |
| 26 | + |
| 27 | +(you'll need to already have `svn` and `wget` available) |
| 28 | + |
| 29 | + cd $(wp plugin path my-plugin --dir) |
| 30 | + bash bin/install-wp-tests.sh wordpress_test root '' localhost latest |
| 31 | + |
| 32 | +where: |
| 33 | + |
| 34 | +* `wordpress_test` is the name of the test database (**all data will be deleted!**) |
| 35 | +* `root` is the MySQL user name |
| 36 | +* `''` is the MySQL user password |
| 37 | +* `localhost` is the MySQL server host |
| 38 | +* `latest` is the WordPress version; could also be `3.7`, `3.6.2` etc. |
| 39 | + |
| 40 | +This script does a couple things. First it installs a copy of WordPress in the `temp/` directory (by default) as well as the WordPress unit testing tools. Then it creates a database to be used while running tests. |
| 41 | + |
| 42 | +NOTE: This script can be run multiple times without errors, but it will *not* overwrite previously existing files. So if your DB credentials change, or you want to switch to a different instance of mysql, simply re-running the script won't be enough. You'll need to manually edit the `wp-config.php` that's installed in the `temp/`. |
| 43 | + |
| 44 | +4) Run the plugin tests: |
| 45 | + |
| 46 | + phpunit |
| 47 | + |
| 48 | +**Note**: phpunit 4.8.x is required (5.x won't work) |
0 commit comments