phpstan/phpstan-phpunit

False positives with `assertSame` on generics with compatible subtypes

oliverklee opened this issue · 2 comments

I have a Collection container class that uses generics:

/**
 * This class represents a list of models.
 *
 * @template M of AbstractModel
 * @extends \SplObjectStorage<M, int>
 */
class Collection extends \SplObjectStorage
{
     …
}

(with AbstractModel being the abstract base class for domain models)

Now I get error messages like this:

  3069   Call to static method PHPUnit\Framework\Assert::assertSame() with      
         OliverKlee\Oelib\DataStructures\Collection<OliverKlee\Oelib\Model\Abs  
         tractModel> and                                                        
         OliverKlee\Oelib\DataStructures\Collection<Tx_Seminars_Model_Organize  
         r> will always evaluate to false.               

(Organizer is a subclass of AbstractModel, as is PaymentMethods used in the example below.)

for code that basically looks like this (simplified):

class Event
{
    /**
     * @return Collection<PaymentMethods>
     */
    public function getPaymentMethods(): Collection;

    /**
     * @param Collection<PaymentMethods> $paymentMethods
     */
    public function setPaymentMethods(Collection $paymentMethods): void;
}

class EvenTest
{
    public function testPaymentMethodsSetsPaymentMethods(): void
    {
        $paymentMethods = new Collection();
        $this->subject->setPaymentMethods($paymentMethods);

        self::assertSame($paymentMethods, $this->subject->getPaymentMethods());
    }
}

So either the check for assertSame should completely disregard the contained type within generics, or it should allow contained types that are compatible to each other.

This could also be caused by, a duplicate of, or related to phpstan/phpstan#5726.

stof commented

To me, this is indeed caused by the linked phpstan issue.