How can you unit test your plugin or theme without WordPress or other dependencies? You simulate the dependencies. My favorite tool to redefine and mock functions is Brain Monkey. In this hands-on testing lab, you will actively write unit tests using Brain Monkey.
The challenge we have when unit testing a plugin or theme is how to force the expected behavior of dependent functions. For objects, we can use Mockery. But for functions, we need another tool.
Huh? For example, your plugin or theme will likely have various WordPress functions, such as
esc_attr, and many others. Right? We use these functions all the time. But how can you unit test your code without loading WordPress?
In this lab, you will dive deep into Brain Monkey to discover how to build unit tests without loading WordPress or any other dependency.
What You Will Learn
In this lab, you will be actively building unit tests as you learn deeply about the process and Brain Monkey. As a test subject, you will write unit tests for
beans_get_post_meta() function in the Beans framework.
- The process of dynamically redefining a function.
- What Brain Monkey is and each of its toolsets.
- Deciding when to use
- How to force a behavior or returned value from a mocked function.
- How to actively test the number of times a function is called.
- How to actively test the arguments being passed to the function.
- and much more.
This lab has several code challenges too.
You get WET when you swim. Stay DRY when you code.
Total Lab Runtime: 03:21:08
- 0 Lab Setupfree 07:07
- 1 The Problem - Why We Need to Simulatefree 24:50
- 2 Behind the Scenes of Redefining a Functionfree 20:31
- 3 Brain Monkey's Toolset Overviewpro 09:04
- 4 Anatomy of the Test Expectationpro 11:51
- 5 setUp and tearDownpro 09:51
- 6 Create a Test Classpro 20:42
- 7 `when()`pro 14:23
- 8 `when()` - Behavior Optionspro 14:26
- 9 `when()` - Code Challengepro 08:27
- 10 `expect()`pro 11:40
- 11 `with()`pro 05:44
- 12 More with `with()`pro 10:02
- 13 `with()` - Code Challengepro 09:53
- 14 `expect()` - Behavior Optionspro 07:47
- 15 `andAlsoExpectIt()`pro 10:46
- 16 `stubs()`pro 04:04
Our themes and plugins use hooks to run code when an event fires. We use WordPress' functions to add or remove a hooked callback, fire the event, or check the status. How do you unit test those interactions without loading WordPress? Meet Brain Monkey. Brain Monkey gives you the power to unit test hooks by simulating WordPress. In this lab, you'll walk through building unit tests for hooks.
Check out the PHP Library for more hands-on labs, insights, Docx, and more.
Check out the series page for more labs: Master Tester Series