惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

美团技术团队
P
Privacy International News Feed
P
Proofpoint News Feed
Security Archives - TechRepublic
Security Archives - TechRepublic
C
CXSECURITY Database RSS Feed - CXSecurity.com
Know Your Adversary
Know Your Adversary
Security Latest
Security Latest
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Attack and Defense Labs
Attack and Defense Labs
NISL@THU
NISL@THU
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
GbyAI
GbyAI
N
News and Events Feed by Topic
N
News | PayPal Newsroom
Y
Y Combinator Blog
C
CERT Recently Published Vulnerability Notes
N
Netflix TechBlog - Medium
S
Security Affairs
Spread Privacy
Spread Privacy
罗磊的独立博客
腾讯CDC
MyScale Blog
MyScale Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
L
LINUX DO - 热门话题
The Cloudflare Blog
L
LangChain Blog
博客园_首页
H
Hacker News: Front Page
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
博客园 - 聂微东
SecWiki News
SecWiki News
A
Arctic Wolf
爱范儿
爱范儿
Google Online Security Blog
Google Online Security Blog
T
Threat Research - Cisco Blogs
Hacker News - Newest:
Hacker News - Newest: "LLM"
有赞技术团队
有赞技术团队
The GitHub Blog
The GitHub Blog
Cyberwarzone
Cyberwarzone
博客园 - 叶小钗
V
Visual Studio Blog
V
V2EX
T
Tailwind CSS Blog
Project Zero
Project Zero
T
The Blog of Author Tim Ferriss
F
Fortinet All Blogs
MongoDB | Blog
MongoDB | Blog
D
Docker

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How Mutation Testing Exposes the Truth (PHP 2026 Edition)
CodeCraft Di · 2026-05-12 · via DEV Community

You've got 85% code coverage. Your CI pipeline is green. You ship to production — and things break in ways your tests never caught. Sound familiar?

I've been there. And for a long time, I thought the answer was more tests. What I actually needed was better tests. That's exactly what mutation testing taught me, and after using Infection PHP in production projects through 2025 and into 2026, I can confidently say it changed how I think about test quality entirely.

Previous article in this category: https://codecraftdiary.com/2026/04/18/laravel-testing-mistakes/


The Dirty Secret of Code Coverage

Code coverage tells you which lines were executed during your test run. It says nothing about whether your assertions are actually meaningful.

Consider this classic trap:

<?php

class OrderDiscountCalculator
{
    public function calculate(float $price, int $quantity): float
    {
        if ($quantity >= 10) {
            return $price * 0.9;
        }

        return $price;
    }
}

Enter fullscreen mode Exit fullscreen mode

And a test that covers it 100%:

<?php

use PHPUnit\Framework\TestCase;

class OrderDiscountCalculatorTest extends TestCase
{
    public function testCalculate(): void
    {
        $calculator = new OrderDiscountCalculator();

        // Both branches hit — 100% coverage!
        $calculator->calculate(100.0, 15);
        $calculator->calculate(100.0, 5);
    }
}

Enter fullscreen mode Exit fullscreen mode

This test covers 100% of the code. It also asserts absolutely nothing. If someone changes 0.9 to 0.5, your test suite stays green while your customers get 50% off everything. That's a very expensive bug.

This is precisely the problem mutation testing solves.


What Is Mutation Testing?

Mutation testing works by automatically introducing small bugs — called mutants — into your source code, then running your test suite against each mutated version. If your tests catch the bug (the mutant is killed), great. If your tests still pass with the bug in place (the mutant survives), you have a gap.

Common mutations include things like:

  • Changing >= to > or <=
  • Replacing + with -
  • Flipping true to false
  • Removing entire return statements

The metric you care about is the Mutation Score Indicator (MSI) — the percentage of mutants your tests kill. A high MSI means your tests are genuinely sensitive to regressions.


Getting Started with Infection PHP

Infection is the de facto mutation testing framework for PHP. It integrates cleanly with PHPUnit and runs as a Composer dev dependency.

composer require --dev infection/infection

Enter fullscreen mode Exit fullscreen mode

Run it for the first time with:

./vendor/bin/infection --threads=4

Enter fullscreen mode Exit fullscreen mode

Infection will run your existing test suite, then start generating and testing mutants. On a modern project with --threads=4, it's fast enough to include in a CI pipeline.


A Real-World Example: Catching What Coverage Misses

Let me walk you through a scenario I actually encountered on a SaaS project — a pricing engine with tiered discounts.

<?php

class TieredPricingService
{
    private const TIERS = [
        100 => 0.70, // 30% discount for 100+
        50  => 0.80, // 20% discount for 50+
        10  => 0.90, // 10% discount for 10+
    ];

    public function getPrice(float $unitPrice, int $quantity): float
    {
        foreach (self::TIERS as $minQuantity => $multiplier) {
            if ($quantity >= $minQuantity) {
                return round($unitPrice * $multiplier * $quantity, 2);
            }
        }

        return round($unitPrice * $quantity, 2);
    }
}

Enter fullscreen mode Exit fullscreen mode

My original tests covered all branches. PHPUnit reported 100% coverage. But when I ran Infection, it flagged a surviving mutant — it changed >= to > in the tier check, and my test for exactly 10 units didn't catch it because I only tested with 11. The boundary condition was untested.

Here's what the corrected test looked like after Infection exposed the gap:

<?php

use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Attributes\DataProvider;

class TieredPricingServiceTest extends TestCase
{
    private TieredPricingService $service;

    protected function setUp(): void
    {
        $this->service = new TieredPricingService();
    }

    #[DataProvider('pricingProvider')]
    public function testGetPrice(float $unitPrice, int $quantity, float $expected): void
    {
        $this->assertSame($expected, $this->service->getPrice($unitPrice, $quantity));
    }

    public static function pricingProvider(): array
    {
        return [
            'below first tier'         => [10.0, 5,   50.00],
            'exactly at 10 tier'       => [10.0, 10,  90.00],  // boundary — was missing!
            'above 10 tier'            => [10.0, 11,  99.00],
            'exactly at 50 tier'       => [10.0, 50,  400.00], // boundary
            'exactly at 100 tier'      => [10.0, 100, 700.00], // boundary
            'above highest tier'       => [10.0, 200, 1400.00],
        ];
    }
}

Enter fullscreen mode Exit fullscreen mode

After adding boundary assertions, Infection's MSI jumped from 61% to 94%. That's the difference between a test suite that gives you false confidence and one that actually has your back.


Configuring Infection for Your Project

Infection is configured via infection.json5 in your project root. Here's a production-ready config I use:

{
    "$schema": "vendor/infection/infection/resources/schema.json",
    "source": {
        "directories": ["src"],
        "excludes": ["src/Infrastructure/Migrations"]
    },
    "mutators": {
        "@default": true
    },
    "testFramework": "phpunit",
    "testFrameworkOptions": "--testsuite=unit",
    "minMsi": 85,
    "minCoveredMsi": 90,
    "threads": 4,
    "logs": {
        "text": "var/log/infection.log",
        "html": "var/log/infection.html",
        "summary": "var/log/infection-summary.log"
    }
}

Enter fullscreen mode Exit fullscreen mode

The minMsi and minCoveredMsi thresholds are important — they let your CI pipeline fail if mutation score drops below acceptable levels, the same way PHPUnit can fail below a coverage threshold.


Integrating Into CI (GitHub Actions)

Here's a GitHub Actions job I've been running since mid-2025:

mutation-testing:
  runs-on: ubuntu-latest
  needs: tests
  steps:
    - uses: actions/checkout@v4

    - name: Setup PHP
      uses: shivammathur/setup-php@v2
      with:
        php-version: '8.3'
        coverage: xdebug

    - name: Install dependencies
      run: composer install --no-interaction

    - name: Run Infection
      run: ./vendor/bin/infection --threads=4 --min-msi=85 --min-covered-msi=90

Enter fullscreen mode Exit fullscreen mode

One important note: Infection requires a coverage driver (Xdebug or PCOV) to know which mutants are relevant to which tests. PCOV is faster for large codebases; Xdebug gives more detail. I use Xdebug locally and PCOV in CI.


Common Objections — And Honest Answers

"It's too slow." It can be on large codebases, but --threads and configuring source.excludes to skip generated code, migrations, and DTOs makes a huge difference. I typically exclude everything that has no business logic.

"The MSI is too low to be useful." Start with --min-msi=0 and just look at the HTML report. Prioritize killing mutants in your core domain logic first — that's where bugs actually hurt.

"It produces too many surviving mutants." Some mutants are genuinely equivalent (they don't change behavior). Infection lets you mark these as ignored in config. Over time your noise floor drops significantly.


What My Workflow Looks Like in 2026

My current approach on active PHP projects:

  1. PHPUnit with strict coverage for the fast feedback loop during development.
  2. Infection on every PR targeting only changed files — using --git-diff-filter (available since Infection 0.27) to keep CI times reasonable.
  3. Full Infection run weekly on the main branch to catch gradual MSI drift.

The --git-diff-filter flag is a game-changer for larger repos — it only mutates code touched in the current diff, so mutation testing stays practical even on monorepos.

./vendor/bin/infection --git-diff-filter=AM --threads=8

Enter fullscreen mode Exit fullscreen mode


Final Thoughts

Code coverage is a floor, not a ceiling. It tells you the minimum — which lines were touched. Mutation testing tells you something far more valuable: whether those lines are protected by tests that would actually catch a regression.

If you're publishing technical content in 2026 and you're not talking about mutation testing, you're leaving one of PHP's most powerful quality tools completely off the table. The tooling has matured, the CI integration is straightforward, and the payoff in confidence is real.

Start with a single service class. Run Infection. Look at what survives. I promise you'll find something surprising.

Resources: