This is more a theory related question.

I'm not looking at the practical ways to do this, as I can find plenty of example (official and not), which however does not explain how it is possible to properly create and run tests for elements of code that relies so much on the system (WordPress) and its features (hooks).

I'm asking that admitting I still lack some general knowledge of unit testing and most likely missing some important point that probably would make this post pointless: I'm sure you will let me know if this is the case! :)

It is also worth noting that all of this came out after reading Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin, which covers strongly typed languages and in particular, is focused in Java development, but really provides so many useful tips (many obvious, still often ignored) that I want to try my best to apply as much as I can on my PHP code, including (clean) unit tests.

So, back to the point...

A test unit is supposed to be atomic, independent (meaning that it does not depend on other tests), and as much as possible encapsulated.

I don't see how this could be possible in a a WordPress plugin, considering at least these aspects:

  • WordPress itself - I need to create a new instance of WP. When? Each time I run a set of tests? On each single test?
  • Hooks - We depend so much on hook that I really can't see how we can create a clean and readable test, without adding all the clutter for handling hooks
  • User interface - Most of what happen in WP is related to the UI (both back and front ends). For instance, how would you test, in the post edit page, the behaviours of a specific button (introduced by the plugin)? And to make it even more complex, what if this button runs an ajax call and changes something in the post edit page, without reloading it?
  • 3
    Did you check out this great answer by @G.M. ?
    – birgire
    Oct 22, 2014 at 10:20
  • Wow, I missed that one! It's very useful and I'm certainly going to follow it. However I still don't get how I'm supposed to test the last item in my list. Oct 22, 2014 at 12:04
  • For the last item there are many solutions, you can check for example how this plugin is using Selenium for UI tests.
    – birgire
    Oct 22, 2014 at 12:16
  • So, I must split test types in two, right? 1. Unit tests 2. (sort of) Integration tests. If I understand correctly, it is not possible to run actual unit tests when the rendered content is involved. In this case, integration tests (with Selenium or any other mean what would emulate user's actions) is the approach that I must use. Oct 22, 2014 at 12:35
  • I've also seen this split into 3 parts, where the additional 3rd part is for the User actions.
    – birgire
    Oct 22, 2014 at 14:29


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.