Steve Grunwell - Testing WordPress

https://stevegrunwell.github.io/confidently-testing-wordpress/#/

Testing Fundamentals

Automated Testing

  • Reduces time + chance of human error
  • Easily reproducible
  • Gateway to CI/CD

Test Types

  • Unit – Test the smallest possible unit of an app. Often a single function
  • Integration – How individual components interact
  • End-to-End(E2E) – An entire path through an application

Automated Testing Pyramid

ROI for Testing

System Under Test (SUT)

  • The system we’re currently testing:
    • A single method
    • A class
    • A whole feature

WordPress Testing is Complicated

  • Tightly-coupled system
  • Difficult to test anything in true isolation

Testing Toolbox

PhpUnit – https://phpunit.de/

Structure

  • Test Suite – Collection of test classes
  • Test Class (class) – Collection of test methods
  • Test Case (method) – A single scenario to be tested

Assertions

  • True or False
  • Equality
  • Verify Contents – contains, regular expression matching
  • Negative Assertions

Test Doubles

Replacing actual systems with test versions.

  • Stub out/mock an API
  • Return known values

Mockery – popular library for creating test doubles

PhpUnit Markup Assertions – Assertions powered by DOMDocument

WP Core Test Suite

Scaffolding Out Test Suite

Generate test scaffolding via WP-CLI

What Do We Get?

  • phpunit.xml.dist
  • .phpcs.xml.dist
  • .travis.yml
  • bin/install-wp-tests.sh
  • tests/bootstrap.php
  • tests/test-sample.php

What We Don’t Get

  • Composer

Bootstrap File

  1. Locate the WordPress installation
  2. Gain access to the tests_add_filter() function.
  3. Load the main plugin file.
  4. Bootstrap WordPress core.

Base Test Class

  • HPUnit\Framework\TestCase
  • WP_UnitTestCase

Fixtures

@Group

Data Providers

  • Methods
  • @testWith

Factories (WordPress)

Generate users, posts, and more for testing.

  • factory->post->create()
  • factory->post->create_and_get()
  • factory->post->create_many()

Impersonating Users (WordPress)

Act as users with different roles & capabilities

go_to() (WordPress)

Change the current page context.

Checking for WP_ERRORs

Was the response an instance of WP_ERROR?

Writing Tests

Arrange – Act – Assert

  • Arrange – Set up the scenario
  • Act – Execute the code
  • Assert – Verify things happened as you expected

Testing Permissions

Registering a Custom Post Type

Testing Hooks

Testing Output

Stubbing HTTP Requests

Basic Test-Driven Development (TDD)

Basic Workflow

  1. Write a failing test to describe the functionality or behavior (Red)
  2. Write the code to make the test pass (Green)
  3. Refactor, rinse, repeat (Refactor)

Regression Tests

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.