Skip to content

PHPUnit Testing Conventions

Steve Jones edited this page Apr 3, 2024 · 2 revisions

This document outlines the conventions for writing and organizing PHPUnit tests. Adhering to these conventions ensures our tests are easy to read, maintain, and navigate.

Introduction

PHPUnit is a programmer-oriented testing framework for PHP. It is an instance of the xUnit architecture for unit testing frameworks. Writing tests in a consistent and standardized way helps in understanding the tests written by others and reduces the learning curve for new contributors.

File Naming Conventions

Tests should be stored in files that follow specific naming conventions for ease of identification and consistency.

  • Suffix: Each test file name must end with Test.php. For example, if you are testing a class named Calculator.php, your test file should be named CalculatorTest.php.
  • Case: Use PascalCase for naming test files. This means the first letter of each word in the file name should be capitalized, and there should be no underscores or dashes. For example, SampleTest.php is correct; sample_test.php is not.

Class Naming Conventions

The name of the test class within each file follows a simple convention to mirror the structure and naming of the classes they test.

  • Each test class should be named exactly as the file it is in. If your test file is CalculatorTest.php, the class name should be CalculatorTest.
  • For tests targeting a specific concrete class in the plugin, the test class should be named after the class it tests with the Test suffix. For example, if you are testing a class named Calculator, the test class should be named CalculatorTest.

Directory Structure

To maintain a clear and navigable structure, the tests should reflect the directory structure of the code they test.

  • Tests must reside in a directory structure that matches the structure of the plugin code they are testing. This means if a class is located in src/Calculator/Basic.php, the corresponding test should be located in tests/Calculator/BasicTest.php.
  • This convention helps in quickly identifying the tests relevant to a specific piece of the codebase and maintains a parallel structure between the code and its tests.

Writing Tests

While this document focuses on naming and organization, remember the purpose of testing: to ensure your code behaves as expected under various conditions. Each test method within your test classes should be named to clearly indicate what aspect or behavior of the method it is testing. Use descriptive method names, even if they are lengthy, to clearly state the test's purpose.

Conclusion

Following these conventions for PHPUnit testing will help maintain consistency, readability, and navigability in the project's tests. It makes it easier for developers to find, understand, and write tests, contributing to the overall quality and reliability of the software.