psalm / psalm-plugin-phpunit

A PHPUnit plugin for Psalm
76 stars 33 forks source link

PHPUnit setup methods should be treated equally to constructors #107

Open morozov opened 3 years ago

morozov commented 3 years ago

PHPUnit executes setUp() and other @before methods on each test run, so with regards to the test (test*() and @test) methods they behave more or less like a constructor.

When analyzing test classes, Psalm and the PHPUnit plugin report the properties initialized in setup methods as not initialized in constructor.

$ composer show | grep psalm
psalm/plugin-phpunit                           0.15.1    Psalm plugin for PHPUnit
vimeo/psalm                                    4.5.2     A static analysis tool for find...
<?php

namespace Tests;

use PHPUnit\Framework\TestCase;
use stdClass;

class ObjectTest extends TestCase
{
    /** @var stdClass */
    private $object;

    protected function setUp(): void
    {
        $this->object = new stdClass();
    }

    public function testObject(): void
    {
        self::assertIsNotNull($this->object);
    }
}
$ psalm tests/ObjectTest.php

ERROR: PropertyNotSetInConstructor - tests/ObjectTest.php:11:13 - PropertyTests\ObjectTest::$object is not defined in constructor of Tests\ObjectTest and in any private or final methods called in the constructor (see https://psalm.dev/074)
    private $object;

While it's technically true, it's irrelevant for the test cases. By the time when the test method is invoked, the property will be initialized.

It is possible to rework such tests to initialize the object explicitly for each test method but this is less convenient, more verbose and in fact invalidates the PHPUnit setup approach.

weirdan commented 3 years ago

An easy, albeit not 100% correct approach could be to suppress PropertyNotSetInConstructor when there's an initializer present (setUp() or @before), similar to how it's done for MissingConstructor.

morozov commented 3 years ago

This is what I'm about to do at the project level but you're right, it will suppress other issues than this. E.g. https://github.com/sebastianbergmann/phpunit/issues/4307 which still exists for some other properties like $backupStaticAttributes and $runTestInSeparateProcess (to be reported to PHPUnit).

VincentLanglet commented 3 years ago

Would it be possible to introduce something like an annotation to tell psalm setup works like a __construct method ?

devbanana commented 2 years ago

Also having this issue. Has there been any progress on this?

VincentLanglet commented 2 years ago

Also having this issue. Has there been any progress on this?

As you can see, the issue is still opened. Feel free to work on it if you look for progress ;)