Skip to content

Conversation

@TomasVotruba
Copy link
Member

@TomasVotruba TomasVotruba commented Jan 27, 2026

PHPUnit 12 introduced requirement for mocks to be used or be stubs. There is quite common use case that breaks this assumption. Mock object defined in in setUp() method, used in multiple test methods, but not defining expectations in all of them. Often these mocks are passed as arguments into a new service defined in setUp() method as well.

This will turn your PHPUnit run into list of NNNNNNs and make test hard to read and impossible to turn off. It seem something is broken, and it forces you to rewrite a lot of tests manually.

Since PHPUnit 12.5.2 you can add special attribute per tests to ignore this notice. More manual dumb work.

This rule automates this process by looking at:

  • is there a MockObject property? ✔️
  • is there a setUp() method? ✔️
  • are there at leats 2 test methods? ✔️
  • is the mock property used either in setUp() method or at least in 2 tests methods? - TODO

Then adds the attribute there, as we obviously want to use the mock this way.


Any further checks we can automate? Keep them coming.

+#[\PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations]
final class SomeClass extends TestCase
{
    private \PHPUnit\Framework\MockObject\MockObject $someMock;

    protected function setUp(): void
    {
        $this->someMock = $this->createMock(\stdClass::class);
    }

    public function testOne()
    {
    }

    public function testTwo()
    {

    }
}

@TomasVotruba TomasVotruba force-pushed the tv-allow-attribute branch 2 times, most recently from ca6112d to 6e454b1 Compare January 27, 2026 11:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants