Practical PHP integration testing with PHPUnit and Mockery
Integration tests prove that a PHP application still behaves correctly when its parts meet: a controller reaches a service, the service writes to MySQL, and a payment or messaging adapter sends a controlled request. They run more slowly than unit tests, yet they catch wiring errors, SQL mistakes, and mismatched assumptions that isolated classes cannot. Learn more about ゲーミングモニターの応答速度設定 Od を変えて残像感ほどほどに保つ方法.
PHPUnit supplies the runner, assertions, lifecycle hooks, and CI-friendly reporting. Mockery creates configurable test doubles for collaborators whose real side effects would be slow, costly, or unsafe. Together, they let a team verify important boundaries without pretending that every external system belongs inside the test.
A useful suite starts with a specific business risk, not a desire to automate every button. For a PHP checkout flow, it might prove that a paid order is stored once and a declined payment leaves nothing behind. The same approach works for a small Laravel agency in Brisbane and a distributed platform team across Sydney and Melbourne.
Defining the integration boundary
Begin by naming what crosses the boundary. A strong integration test might send an HTTP request through a route and service into a real MySQL schema while replacing only the payment provider with a controlled double. Another may run a repository against the production database engine but use a local HTTP server for its outbound call.
Choose fidelity according to risk. SQLite is quick, but it cannot reproduce MySQL collations, locking, SQL modes, and transaction behaviour. Run MySQL in a container or against a dedicated test schema, and apply every migration before each suite. Never point an integration test at production or a shared development database.
Write the expected contract before coding: inputs, outputs, persisted rows, emitted messages, and failure behaviour. For an Australian online shop, one scenario can cover an A$125 GST-inclusive order, correct tax fields, and the refund path required for a faulty purchase under the Australian Consumer Law. Stable fixtures make that contract repeatable.
Building a repeatable test harness
Install compatible development dependencies with composer require --dev phpunit/phpunit mockery/mockery, then organise tests under directories such as tests/Integration.
Provide the suite with explicit environment variables for the database DSN, cache, and HTTP endpoints. PHPUnit configuration can supply testing-only defaults, while secrets should come from the CI secret store. This prevents a developer’s .env file from silently redirecting a destructive test.
Build data through small factories rather than dumping shared SQL into each method. Give each test a customer, order, and payment reference it can modify without colliding with neighbours. Freeze timestamps through an injected clock, and avoid random values unless the test records the generated seed.
Mocking external dependencies
Use Mockery when the boundary is an interface you own or a nondeterministic outbound collaborator. Expectation-based doubles are useful when timing is part of the behaviour:
use Mockery;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use PHPUnit\Framework\TestCase;
final class CheckoutIntegrationTest extends TestCase
{
use MockeryPHPUnitIntegration;
public function testPaidOrderIsPersisted(): void
{
$gateway = Mockery::mock(PaymentGateway::class);
$gateway->shouldReceive('charge')
->once()
->with(12500, 'AUD')
->andReturn(new ChargeResult('pay_123'));
$repository = new PdoOrderRepository($this->pdo());
$service = new CheckoutService($gateway, $repository);
$receipt = $service->checkout('order-17', 12500, 'AUD');
self::assertSame('pay_123', $receipt->paymentId());
self::assertSame('pay_123', $repository->paymentReference('order-17'));
}
}
Here, $this->pdo() is a test helper that returns the migrated disposable MySQL connection. The with constraint catches errors such as charging cents rather than dollars, while once prevents duplicate payment attempts. Include rejection, timeout, and malformed-response cases through separate doubles. Keep value objects and pure calculations real; mocking them adds noise without testing a boundary.
For third-party APIs, prefer a small fake or a local contract server such as WireMock over hand-written Mockery classes. It can replay a provider-shaped response and prove that your adapter maps fields correctly. Australian shops often need controlled Afterpay, Australia Post, or banking responses; fixtures let them test those paths without sending real requests or exposing customer data.
Exercising persistence and transactions
Database cleanup deserves deliberate design. A transaction rolled back after each test is fast, but it can hide a broken commit, a failed retry, or code that opens a second connection. Use a database cleaner, disposable schemas, or fresh containers when the scenario exercises transaction boundaries, and randomise test order to expose hidden dependencies.
A migration rehearsal is also valuable before a production move; this account of a minimal-downtime RDS migration shows why cutover timing and replication lag deserve tests rather than optimism. Record the maximum tolerated age of replicated data, verify the final delta, and make rollback an explicit decision.
AWS teams can rehearse against MySQL in the Asia Pacific Sydney or Melbourne region, but spinning up RDS for every commit is usually wasteful. A local MySQL container gives fast feedback, followed by a scheduled staging RDS smoke test using synthetic data. That split catches engine-specific issues without turning CI into a cloud bill.
Running tests in Australian CI pipelines
Keep the pipeline deterministic. A self-hosted runner in Sydney or Melbourne can keep database traffic in the same AWS region, while developers in Perth or Brisbane use the same container image and locked Composer dependencies. Run unit tests first, then the integration suite, and cache Composer packages by the lock file rather than the branch name.
Store and log in UTC, but exercise business timestamps in the intended Australian zone. Sydney and Melbourne observe daylight saving, while Brisbane does not, so a recurring billing or dispatch window can fail twice a year. Explicitly test the boundary before and after a clock change instead of hiding the risk in date_default_timezone_set().
Privacy rules belong in the harness. For organisations covered by the Privacy Act 1988, generate synthetic identities and mask personal details in diagnostics. The Australian Privacy Principles and Notifiable Data Breaches scheme make accidental exposure costly, so logs, database snapshots, and CI artefacts should contain test records only.
Diagnosing failures and keeping tests useful
Make a failure explain itself. Include the order reference, relevant external response, and current test phase, while keeping credentials out of the message. Replace arbitrary sleeps with bounded polling, and assert the observable result rather than a private method call. A useful failure tells the next engineer where the boundary broke.
Change one source of delay at a time. The same diagnostic restraint appears in a response-time tuning guide, where changing a monitor’s overdrive setting reduces ghosting without creating another artefact. In tests, measure connection, query, and HTTP durations separately, then widen only the timeout that genuinely needs it.
Track flaky tests as defects with an owner and an expiry date, not permanent exceptions. Remove shared state, freeze random seeds, and use unique external identifiers. Each retained test should protect a meaningful workflow, so a suite that grows from 400 milliseconds to eight seconds still earns its place in the delivery gate.
Start with the riskiest owned workflow in your PHP application. Write one failing integration test around it, run it against disposable MySQL, mock only the unstable boundary, and let the failure guide the design. Repeating that loop creates a suite that developers trust because every test proves something operational.
Teams can contact Karl about an independent review of their PHPUnit harness, AWS migration path, or systems architecture. Carrying the same test into an Australian CI pipeline with synthetic data and the production database engine turns a fragile collection of scripts into a dependable release signal.
Karl Katzke