WooCommerce Unit Tests
$ phpunit --version
Install WordPress and the WP Unit Test lib using the
install.shscript. Change to the plugin root directory and type:
$ tests/bin/install.sh <db-name> <db-user> <db-password> [db-host]
<db-password> will be set as given. Previously, you would have needed to escape certain characters (forward & backward slashes, and ampersand), but install.sh now escapes them when it needs to internally. You may still need to quote strings with backslashes to prevent them from being processed by the shell or other programs.
$ tests/bin/install.sh woocommerce_tests root root # The actual password only has a single backslash, but it's escaped # to prevent the shell and PHP from treating it as a backspace character $ tests/bin/install.sh woocommerce_tests root 'a\\b/&' # Previously, the password would have had to be passed as 'a\\\\b\/\&'
<db-name> database will be created if it doesn't exist and all data will be removed during testing.
Simply change to the plugin root directory and type:
The tests will execute and you'll be presented with a summary. Code coverage documentation is automatically generated as HTML in the
You can run specific tests by providing the path and filename to the test class:
$ phpunit tests/unit-tests/api/orders
A text code coverage summary can be displayed using the
$ phpunit --coverage-text
- Each test file should roughly correspond to an associated source file, e.g. the
formatting/functions.phptest file covers code in the
- Each test method should cover a single method or function with one or more assertions
- A single method or function can have multiple associated test methods if it's a large or complex method
- Use the test coverage HTML report (under
tmp/coverage/index.html) to examine which lines your tests are covering and aim for 100% coverage
- For code that cannot be tested (e.g. they require a certain PHP version), you can exclude them from coverage using a comment:
// @codeCoverageIgnoreEnd. For example, see
- In addition to covering each line of a method/function, make sure to test common input and edge cases.
assertSame()where possible as it tests both type & equality
- Remember that only methods prefixed with
testwill be run so use helper methods liberally to keep test methods small and reduce code duplication. If there is a common helper method used in multiple test files, consider adding it to the
WC_Unit_Test_Caseclass so it can be shared by all test cases
- Filters persist between test cases so be sure to remove them in your test method or in the
- Use data providers where possible. Be sure that their name is like
data_provider_function_to_test(i.e. the data provider for
data_provider_test_is_postcode). Read more about data providers here.
Tests are automatically run with Travis-CI for each commit and pull request.