project-testing
Use when writing or modifying PHPUnit tests: unit, integration, WebTestCase or mock setup.
- License 许可
- AGPL-3.0
- 所属仓库
- loupe-ac/loupe
- 最近更新
- 2026-11-15
- Stars
- ★ 2
- Forks
- 0
01 前言 Front Matter
- name
- project-testing
- description
- Use when writing or modifying PHPUnit tests: unit, integration, WebTestCase or mock setup.
03 SKILL.md 正文
Testing, PHPUnit patterns
WebTestCase, mocking services across multiple requests
Call $client->disableReboot() whenever a mock must survive a GET then POST sequence. Symfony shuts the kernel down after each $client->request() call. This discards any getContainer()->set(ServiceClass::class, $mock) override. The next submitForm() call boots a fresh kernel and uses the real service. Add disableReboot() before the first request in any test that both mocks a service and makes two or more HTTP requests.
$client = static::createClient();
$client->disableReboot(); // keep mock alive across GET + submitForm
$this->mockExternalService($data);
$client->request('GET', '/confirm?id=123');
$client->submitForm('Save', [...]);
You need this only when the handler, and not just the controller, calls the mocked service. The usual trigger is an API call that moves from the controller's GET prefill into the command handler's POST flow.
Controller integration tests, assert DB state
For a POST endpoint (create, update, delete, attach, detach), assert the database outcome as well as the redirect. A test that asserts only assertResponseRedirects(...) tests routing. Assert after you follow the redirect.
$em->clear(); // discard identity-map cache
$fetched = $em->find(Project::class, $project->id);
self::assertNull($fetched); // for a delete
// or
self::assertNotNull($fetched->repository); // for an attach
Stale identity-map state in test setup
A test that persists the inverse side of a relationship does not update the owning entity. new GitHubRepository($project, ...) sets repo.project = $project, but leaves project.repository = null in memory. A later $client->request() can make the controller load that owning entity through MapEntity. Doctrine then returns the cached object instead of a fresh SQL fetch. The property is still null, so any handler that reads it does nothing, with no error.
Call $em->clear() after all setup writes and before the first $client->request().
$em->persist($repo);
$em->flush();
$em->clear(); // force fresh fetch during the subsequent HTTP request
$client->loginUser($user);
$client->request(...);
PHPUnit mock discipline
PHPUnit 13 emits an N ("PHPUnit Notice") for every createMock() call that never configures expects().
- Use
createStub()for a dependency that only needs return values, with no call verification. Declare the property asFoo&Stub. - Use
createMock()only when you verify calls withexpects($this->once())or similar. Declare the property asFoo&MockObject.
// ✗ createMock() without expects() → PHPUnit 13 notice
private EntityManagerInterface&MockObject $em;
$this->em = $this->createMock(EntityManagerInterface::class);
// ✓ pure stub — only return values, no call-count assertion
private EntityManagerInterface&Stub $em;
$this->em = $this->createStub(EntityManagerInterface::class);
// ✓ mock with explicit expectation
private UserRepository&MockObject $repo;
$this->repo = $this->createMock(UserRepository::class);
$this->repo->expects($this->once())->method('findOneByEmail')->willReturn(null);
Update the use import to match: use PHPUnit\Framework\MockObject\Stub; or use PHPUnit\Framework\MockObject\MockObject;. Watch for N characters in the test output and for the "OK, but there were issues!" summary line. These are framework-level notices, and they differ from PHP E_NOTICE.
WebTestCase, assert on stable hooks, not markup structure
WebTestCase crawler assertions couple to the rendered markup, so a visual refactor breaks them with no warning. assertCount(1, $crawler->filter('tbody tr')) fails the moment a <table> becomes .lp-doc-row divs. Prefer stable hooks over structural or positional selectors.
- Use a
data-*attribute, a route-boundid, or a.lp-*component class, such as$crawler->filter('[data-document-id]'),'.lp-doc-row'or'[data-controller="…"]'. - Do not use tree position or raw HTML tags that a template redesign moves, such as
'tbody tr','table td'or'div > span:first-child'.
This mirrors the Playwright selector-scoping rule in project-e2e. Assert on intent-carrying hooks that the markup is unlikely to drop.
A test that cannot fail is worse than no test
A negative assertion says "no query was issued", "no email was sent", or "this list is empty". It passes trivially when the operation under test never ran at all. Assert first that the operation happened, then that the specific effect is absent.
// Guard: without this, the assertion below also passes on a request that
// ran no queries whatsoever, proving nothing about the skip.
self::assertNotEmpty($statements);
self::assertSame([], array_values(array_filter(
$statements,
static fn (string $sql): bool => str_contains($sql, 'UPDATE oauth_credentials'),
)));
A test for an optimization must fail when the optimization is removed. Verify that explicitly. Temporarily revert the guard, watch the test fail, and restore it. Say in the commit message that you did.
An assertion on collected queries uses the profiler, which is off by default in
test (framework.profiler.collect: false). Call $client->enableProfiler() before
the request, then $client->getProfile(). Narrow the result with
assertInstanceOf(Profile::class, ...). assertNotFalse() does not narrow
null, so phpstan rejects the next method call.
Rate limiters
Every rate limiter needs a when@test override with a high limit, and you test its throttle with a hand-built factory. When you add a limiter under framework.rate_limiter in config/packages/framework.yaml, add a matching entry under the when@test block of that file. Give it a high limit, for example 1000. The rest of the suite is then never throttled. Test the throttling in isolation with a low-limit factory built directly.
$factory = new RateLimiterFactory(
['id' => '<name>', 'policy' => 'fixed_window', 'limit' => 2, 'interval' => '1 minute'],
new InMemoryStorage(),
);
A bearer token in a WebTestCase
Loupe accepts no static token, so a test that calls /api or /mcp needs an
OAuth access token. Mint one rather than run a grant.
$token = AgentCredential::agentToken(static::getContainer(), $owner);
$project = AgentCredential::tokenFor(static::getContainer(), $owner, 'mcp', $project);
App\Tests\Support\AgentCredential calls MintAccessTokenHandler, which
exists in dev and test alone. The token comes from the repositories the grants
use, so the firewall accepts it, and MintAccessTokenHandlerTest proves that
over HTTP.
Pass base scopes only, such as agent, mcp or site-review. The handler adds
the binding. A scope that needs a project takes the one you name, or every
project of the owner. The agent scope needs none, so naming a project with it
throws.
Never mint in a test about signing in. The authorization code flow, the device
flow and the widget popup have their own tests under tests/Module/OAuth/, and
a shortcut there would prove nothing.
For a KernelTestCase that needs a security token rather than a bearer, use the
McpTokenScenario trait, which sets an AuthenticatedCredential directly.
Terms acceptance in a WebTestCase
A fixture User has not accepted the terms, so RequireTermsAcceptanceListener
diverts an authenticated HTML request to the interstitial. The symptom is an
unexplained 302 to /terms/accept in a test that has nothing to do with
terms. Readers usually mistake it for a broken redirect or a lost session.
Stamp the fixture.
$user = new User(fullName: 'Riley Chen', email: 'riley@example.com', password: 'x');
AcceptedTerms::stamp($user, static::getContainer());
$em->persist($user);
App\Tests\Support\AcceptedTerms reads app.terms.version, so a bump to that
parameter does not invalidate the fixtures.
The gate stays live in the test environment on purpose. An inert gate costs
three lines instead of a stamp per fixture. But the rest of the suite would then
run a configuration production never uses. A regression where the gate fires
when it should not would then pass unnoticed. The tests that are about the gate,
RequireTermsAcceptanceListenerTest and AcceptTermsControllerTest, build their
users without the stamp.
Database isolation between tests
dama/doctrine-test-bundle wraps each test in a database transaction and rolls it back, so you need no custom schema-reset code. Schema creation runs once in tests/bootstrap.php, which drops, creates and migrates. Never write a resetSchema() method that drops and recreates the schema per test.
04 同仓库更多 Skills
loupe-workers
Use when reading worker runs or bridges through the loupe MCP, stopping, resuming or holding workers, cancelling a bridge command, or recovering workers after a usage limit or network outage.
loupe-site-review
Use when acting on live-review feedback through the loupe MCP: reading the feedback of a card or project, fixing it, or marking it addressed.
loupe-inbox
Use when an agent needs a decision, answer or review from the project owner through the loupe MCP, hands a question or to-do to a person, resumes after an ask closed, or needs its session id.
loupe-documents
Use when writing or revising a document for the Loupe app through the loupe MCP, such as a plan, spec, RFC, audit report or retrospective.
loupe-discovery
Use when a bridge runs a discovery run of a Loupe project, when a prompt names loupe-discovery, or when writing a readiness report.
loupe-board
Use when working a Loupe project board through the loupe MCP: reading or writing a card, moving a card, changing the columns, or linking a document or a pull request to a card.