Method 'setMethods' is deprecated when try to write a PHP Unit Test
Asked Answered
A

3

12

I want to create a mock to replace a resource:

$gateway = $this->getMockBuilder('PaymentGateway')
            ->setMethods(['transfer'])
            ->getMock();

I got this warning:

Method 'setMethods' is deprecated

How can I resolve this deprecation?

Adopted answered 30/11, 2020 at 14:14 Comment(0)
S
24

From now on we are supposed to use either onlyMethods() (which would be the closest equivalent to setMethods() and addMethods():

$gateway = $this->getMockBuilder('PaymentGateway')
            ->onlyMethods(['transfer'])
            ->getMock();

This is explained in the PR (linked from the method PHP doc directly, as seen here).

Scintillant answered 30/11, 2020 at 14:26 Comment(4)
thank you for your answer : I replaced setMethods with onlyMethods and i got warning about Class PaymentGateway does not exist !Adopted
That’s a different issue. Unrelated with the original question. You should probably pass the fully qualified class name. Or PaymentGateway::classScintillant
when i use addMethods my test is OK and i don't get warnings, i understand that i sould modify my code to work with onlyMethods. ThanksAdopted
I wish the warnings populating in IDEs would point users to a deprecated functions replacement so we wouldn't need to dig around the internet for it.Manvil
Q
-1

I have managed like this:

$pageModel = $this->getMockBuilder(PageModel::class)
    ->setConstructorArgs($pageModelArguments)
    ->onlyMethods(['getHitQuery'])
    ->enableOriginalClone()
    ->getMock()
;

the enableOriginalClone did the job for me.

Quiescent answered 24/11, 2023 at 12:7 Comment(0)
S
-1

I had the same:

Before:

    $mockHttp = $this
      ->getMockBuilder('GuzzleHttp\Client')
      ->disableOriginalConstructor()
      ->setMethods(['get', 'getBody'])
      ->getMock();
    $this->mockHttp = $mockHttp;

After:

    $mockHttp = $this
      ->getMockBuilder('GuzzleHttp\Client')
      ->disableOriginalConstructor()
      ->addMethods(['getBody'])
      ->onlyMethods(['get'])
      ->getMock();
    $this->mockHttp = $mockHttp;
Swivet answered 6/12, 2023 at 12:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.