Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

getObjectForTrait() does not work for traits that declare a constructor #3722

Closed
oumarkonate opened this issue Jun 14, 2019 · 1 comment

Comments

@oumarkonate
Copy link

commented Jun 14, 2019

Q A
PHPUnit version PHPUnit 6.5.14
PHP version PHP 7.3.5
Installation Method Composer

I test the following trait:

trait MyTrait
{
    /**
     * @var UrlInterface
     */
    private $url;

    /**
     * @param UrlInterface $url
     */
    public function __construct(UrlInterface $url)
    {
        $this->url = $url;
    }

    /**
     * @return string
     */
    public function method1(): string
    {
        return '';
    }

    /**
     * @return string
     */
    public function method2(): string
    {
        return $this->url->generate($this->otherObject);
    }
}

The test class is :

class MyTraitTest extends \PHPUnit\Framework\TestCase
{
    protected $myTrait;

    protected $url;

    public function setUp()
    {
        $this->url = $this->createMock(UrlInterface::class);

        $this->myTrait = $this->getObjectForTrait(myTrait::class, [$this->url]);
    }

    /**
     * Test method method1.
     */
    public function testMethod1()
    {
        $this->assertEmpty($this->myTrait->method1());
    }

    /**
     * Test method method2.
     */
    public function testMethod2()
    {
        $this->url->expects($this->once())
            ->method('generate')
            ->willReturn('some-string');

        $this->assertEquals('some-string', $this->myTrait->method2());
    }
}

The console output when I launch the test:

  1. MyTraitTest::testMethod2
    Error: Call to a member function generate() on null

After analysis, I found variable $arguments is not used in method getObjectForTrait().

image

I know it's not a good practice to put the constructor in trait ... but PHP does not forbid it.

Can you fix that please?

@sebastianbergmann sebastianbergmann changed the title Unused argument $arguments for method getObjectForTrait() getObjectForTrait() does not work for traits that declare a constructor Jun 16, 2019

@oumarkonate

This comment has been minimized.

Copy link
Author

commented Jun 16, 2019

@sebastianbergmann Thanks for the fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants
You can’t perform that action at this time.