Skip to content

Best practices

Chase Wiseman edited this page Aug 26, 2020 · 2 revisions

Unit & integration

Good unit and integration tests should:

  • Be as self-contained as possible
  • Not contain their own logic, like conditionals or loops
  • Only contain a single assert, when possible

Single asserts & logic

Each test ideally should have only one assert statement. A failing assert stops the test’s execution, so any asserts after it will not be evaluated. There is a tradeoff, however, depending on the complexity of the tests. If breaking up multiple asserts into multiple tests would introduce too much complexity or hinder the test's speed, we can make notes for why multiple asserts are the best choice.

Tests should also avoid containing their own logic, such as if/else or foreach. These structures increase the test’s complexity, and often end up testing their own logic on top of the test subject. It can be easily to accidentally skip running some code that’s meant to be tested due to faulty logic.

Data providers

In cases where we need to test multiple input or output of a single method, we can use data providers. These can be implemented in both unit and integration tests.

Unit tests

Unit tests are fast, fully self-contained tests that should not require an instance of WordPress or WooCommerce to pass.

Great candidates for unit tests are simple utility classes, like those that perform string manipulation, or self-contained objects like an API response class. In most cases these types of classes can be tested easily for input and output.

Mocking

While mocking should be used sparingly in general, some light mocking can be used for inconsequential WordPress functions to ease unit testing. Some good candidates for mocking are translation functions like __() that might be used within a tested method. In that case we don’t need to test the behavior of the translation itself, so the method can be bypassed.

On the other hand, if mocks would be needed for more complex objects then integration tests are likely a better solution.

Integration tests

TODO

Clone this wiki locally