Use Mockery to mock a static method called in another static method
Asked Answered
D

1

8

I want to mock a static method which has been used in another method using Mokcery,Just as follows:

Class SomeClass
{
   public static function methodA()
   {
     .....;
     self::B();
   } 
   public static function methodB()
   {
     Do SomeThing
   }
}

if I want to mock methodB,and use methodA,the mock function doesn't work, just because methodB is used in methodA,just as below

 use Mockery as m;
   $mocktest = m::mock->('SomeClass[B]');
   $mocktest->shouldReceive('B')->andReturn("expectedResult");
   $mocktest->methodA();

The code above will result in methodB still return it's original result rather than 'expectedResult'. I expect the methodB used in the methodA to be mocked,how could I operate?

Dawkins answered 10/3, 2016 at 8:16 Comment(0)
J
11

You need to use an alias to mock a static method:

$mock = \Mockery::mock('alias:SomeClass');

Note that class can't be loaded yet. Otherwise mockery won't be able to alias it.

More in the docs:

Just be warned that mocking static methods is not a good idea. If you feel like you need it you have problem with design. Mocking the class you're testing is even worse and indicates your class has too many responsibilities.

Jonahjonas answered 10/3, 2016 at 11:54 Comment(2)
Thanks for your help.But what I wanna do now is mocking a static method that has been called in another static method,not just mocking a simple static method.Dawkins
In my case, to make testing possible, I created a non-static wrapper function around the Laravel job dispatch call (and the wrapper was then mockable): public function dispatchCustomMailableJob($contactId, $executeAt, $customMailable) { SendEmailJob::dispatch($contactId, $executeAt, $customMailable); }Wrench

© 2022 - 2024 — McMap. All rights reserved.