Skip to content

[Bug]: Phpstan does not recognize methods from traits used in test files #1815

Description

@colinmackinlay

What Happened

When a test uses a trait as well as extending a test case it can pass correctly but running phpstan looks for the method in the test case and doesn't check the trait.

How to Reproduce

Create a trait to use in the test:

<?php

namespace Traits;

trait Foo
{
    protected function foo(): bool
    {
        return true;
    }
}

Then use the trait in a test: Tests\Unit\PhpstanTest.php

<?php

use Traits\Foo;
use Tests\TestCase;

pest()->extend(TestCase::class);

pest()->use(Foo::class);

test('a trait method used in a test file is not recognised by phpstan', function () {
    expect($this->foo())->toBeTrue();
});

The test passes but phpstan reports an error as it cannot find the method in TestCase

  11     Call to an undefined method Tests\TestCase::foo().                                 
         🪪  method.notFound                                                                      
         at Tests\Unit\PhpstanTest.php:11                                              
  11     Unable to resolve the template type TValue in call to function expect                    
         🪪  argument.templateType                                                                
         💡  See: https://phpstan.org/blog/solving-phpstan-error-unable-to-resolve-template-type  
         at Tests\Unit\PhpstanTest.php:11 

It behaves the same way if the use is chained:

pest()->extend(TestCase::class)->use(Foo::class);

Sample Repository

No response

Pest Version

5.0.2 and pestphp/pest-plugin-phpstan 5.0.0

PHP Version

8.5.9

Operation System

Windows

Notes

Sorry to find another bug - this upgrade to Pest is still magic!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions