Skip to content

False positive when using assertNull and assertSame on same method #25

@BluePsyduck

Description

@BluePsyduck

Summary of a problem or a feature request

When asserting a method result to be null, then changing the internal state of the object, and then asserting the method result to be the same as some object, PHPStan currently fails thinking it will still be null, letting assertSame() always fail.

Code snippet that reproduces the problem

<?php

declare(strict_types=1);

class Foo {
    /**
     * @var Bar|null
     */
    protected $bar;

    /**
     * @return Bar|null
     */
    public function getBar(): ?Bar
    {
        return $this->bar;
    }

    /**
     * @param Bar|null $bar
     */
    public function setBar(?Bar $bar): void
    {
        $this->bar = $bar;
    }
}

class Bar
{
}

class FooTest extends TestCase
{
    public function testBar(): void
    {
        $foo = new Foo();
        $bar = new Bar();

        $this->assertNull($foo->getBar());
        $foo->setBar($bar);
        $this->assertSame($bar, $foo->getBar()); // <-- This line triggers the error
    }
}

Used configuration

parameters:
  level: max

includes:
  - vendor/phpstan/phpstan-phpunit/extension.neon
  - vendor/phpstan/phpstan-phpunit/rules.neon
  • phpstan/phpstan @ 0.10.2
  • phpstan/phpstan-phpunit @ 0.10

Actual output

 ------ --------------------------------------------------------------------------------------------------------------------------------------- 
  Line   FooTest.php                                                                                                                            
 ------ --------------------------------------------------------------------------------------------------------------------------------------- 
  18     Call to method PHPUnit\Framework\Assert::assertSame() with FactorioItemBrowser\ExportData\Bar and null will always evaluate to false.  
 ------ --------------------------------------------------------------------------------------------------------------------------------------- 
                                                                                                                       
 [ERROR] Found 1 error      

Expected output

 [OK] No errors   

PHPUnit test does run successfully, and so should PHPStan, as all asserts are valid.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions