Automatic Testing in PHP

Table of Contents

  • Linting
  • Static Analysis
  • Unit Testing

Linting

What is Linting?

  • Linting is the process of running a program that will analyse code for potential errors
  • Linting is usually done before the code is committed
  • Linting is usually done on the developer's machine and on the CI server

Linting

Goals

  • make sure the code is valid from a syntax point of view
  • make sure the code follows standards in terms of formatting
  • reduce the manual effort in code reviews

Linting

Tools

  • PHP Code Sniffer
  • PHP Parallel Lint

Linting

Configuration (gitlab)

# .gitlab-ci.yml
php-lint:
  stage: test
  image: php:8.1-cli
  script:
    - vendor/bin/parallel-lint --exclude vendor/ .
psr-12-lint:
  stage: test
  image: php:8.1-cli
  script:
    - vendor/bin/phpcs --standard=PSR12 --extensions=php --ignore=vendor/ .

Static Analysis

What is Static Analysis?

  • Static Analysis is analysing code without running it
  • Static Analysis is usually done before the code is committed
  • Static Analysis is usually done on the developer's machine and on the CI server

Static Analysis

Goals

  • find potential bugs in the code
  • find potential performance issues in the code
  • find potential security issues in the code

Static Analysis

Tools

  • Psalm
  • PHPStan
  • Phan

Static Analysis

Configuration (gitlab)

# .gitlab-ci.yml
static-analysis-psalm:
    stage: test
    image: php:8.1-cli
    script:
    - vendor/bin/psalm --show-info=false
static-analysis-phpstan:
    stage: test
    image: php:8.1-cli
    script:
    - vendor/bin/phpstan analyse --no-progress
static-analysis-phan:
    stage: test
    image: php:8.1-cli
    script:
    - vendor/bin/phan

Unit Testing

What is Unit Testing?

  • Unit Testing is testing a small unit of code in isolation
  • Unit Testing is usually done before the code is committed
  • Unit Testing is usually done on the developer's machine and on the CI server

Unit Testing

Goals

  • provide fast feedback for developers
  • make sure the code does only what it is supposed to do
  • make sure there are no regressions
  • make sure the code is easy to change
  • make sure mistakes are caught early

Unit Testing

Tools

  • PHPUnit
  • infection

Unit Testing

Configuration (gitlab)

# .gitlab-ci.yml
unit-test:
  stage: test
  image: php:8.1-cli
  script:
    - vendor/bin/phpunit --coverage-text
mutation-test:
  stage: test
  image: php:8.1-cli
  script:
    - vendor/bin/infection --min-msi=60 --min-covered-msi=60
Thank you for your time!