So, I'm trying to write a unit test for a piece of code that uses a facade, and it looks like this:
public function test() {
MYFACADE::doSomething();
}
and in the unit test, I am trying to mock the facade call:
MYFACADE::shouldReceive('doSomething')
->once()
->andReturn(false);
The only problem with this is that when Laravel tries to make an instance of underling class for the MYFACADE
, it will of course run the constructor, and right there, is hardcoded database connection call. So without changing my facade, and removing database connection from the constructor of the facade class, is there any way to mock facade call without running the constructor of facade ?
UPDATE: Rest of the setup:
Facade class
class MyFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'myfacade';
}
}
app.php
$app->register(App\Providers\MyServiceProvider::class);
class_alias('App\Facades\MyFacade', 'MYFACADE');
Service provider:
class MyServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('myfacade', function()
{
return new myClasThatDoesSomething();
});
}
}
The underlying class used by facade
class myClasThatDoesSomething
{
public function __construct()
{
// opens db connection here
}
public function doSomething()
{
}
}
example class that uses facade:
class TestClass
{
public function testMethod()
{
$returnValue = MYFACADE::doSomething();
return $returnValue;
}
}
Unit test that checks if the testMethod() returns 'testValue';
MYFACADE::shouldReceive('doSomething')
->once()
->andReturn('testValue');
$instance = new TestClass();
$value = $instance->testMethod();
$this->assertEquals('testValue', $value);