I have had a few situations where…
- I cannot use a normal mock because the object being mocked is hard coded (ie uses new
SomeName()instead of using dependency injection ways). [and…] - I cannot use Mockery’s alias: or overload: mocks because the class has already been loaded. [and…]
- I cannot use Laravel’s facade mocks because the class is not a facade.
So as a last resort, I have created a class within the same file as the test, called Mock_Class_Name and used PHP’s alias() function to replace the real class that I want to mock with my class.
A problem with this is – unless it is a Laravel alias – I can’t simulate any sort of partial mocking so my class has to define ALL functions which get called and not just the ones I want to mock. (If it’s a Laravel alias which is being mocked, then I can just extend the real class but that does not work normally.)
Pseudo example:
class someTest extends TestCase {
publicfunction firstTest(){
class_alias(Support_Class_Mock::class, 'SupportClass');
//// rest of test code here
}
}
class Support_Class_Mock extends AppSupportClass
{
public static function oauthGetAccessToken($beep,$boop){
return 'OAuth Successful';
}
}
My question:
Is what I am doing an acceptable “last resort” practice? (Or is there a better way?)