Skip to content

Report undefined methods in ->method('...') on unions of mocks - #231

Merged
alies-dev merged 14 commits into
psalm:masterfrom
alies-dev:feat/223-mock-union-method
Nov 9, 2026
Merged

alies-dev merged 14 commits into
psalm:masterfrom
alies-dev:feat/223-mock-union-method

Conversation

@alies-dev

@alies-dev alies-dev commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Psalm does not report an undefined method in ->method('...') when the double is a union of mocks or stubs, only when it is a single mocked type.

Before

<?php
/** @psalm-mutable */
interface Mailer {
    /** @psalm-impure */
    public function send(): bool;

    /** @psalm-impure */
    public function sendInvoice(): bool;
}

/** @psalm-mutable */
interface Notifier {
    /** @psalm-impure */
    public function send(): bool;
}

final class MyTestCase extends TestCase {
    public function testMissingOnOneType(bool $flag): void {
        $mock = $flag ? $this->createMock(Mailer::class) : $this->createMock(Notifier::class);
        $mock->method('sendInvoice')->willReturn(true); // no issue
    }

    public function testInlineUnion(bool $flag): void {
        ($flag ? $this->createMock(Mailer::class) : $this->createMock(Notifier::class))->method('sendInvoice'); // no issue
    }
}

After

        $mock->method('sendInvoice')->willReturn(true); // UndefinedMethod: Trying to mock an undefined method NS\Notifier::sendInvoice()
        ($flag ? $this->createMock(Mailer::class) : $this->createMock(Notifier::class))->method('sendInvoice'); // UndefinedMethod: Trying to mock an undefined method NS\Notifier::sendInvoice()

Each member of the union lacking the method gets its own issue. Members that are not doubles (such as null in Mailer&MockObject|null) are skipped, so such a nullable mock is now checked too.

Fixes #223

@alies-dev alies-dev self-assigned this Nov 9, 2026
@alies-dev
alies-dev force-pushed the feat/223-mock-union-method branch from 688a03c to 340a8c1 Compare November 9, 2026 21:56
@alies-dev
alies-dev marked this pull request as ready for review November 9, 2026 22:09
@alies-dev
alies-dev merged commit dc3161b into psalm:master Nov 9, 2026
8 checks passed
@alies-dev
alies-dev deleted the feat/223-mock-union-method branch November 9, 2026 22:41
@alies-dev

Copy link
Copy Markdown
Contributor Author

Known limitation: ->expects(...)->method('...') is only checked when expects() has a single PHPUnit expectation builder type (isExpectationBuilder() requires a single atomic). If the union also contains a domain class with its own expects(), the result of expects() is a union, it is not unwrapped, and method('...') on it is not checked.

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.

Check ->method('...') on unions of mocks

1 participant