How to unit test functions that use type hinting

mocking, phpunit, symfony, type-hinting, unit-testing

Solution

Use full namespace when you use mocking, it will fix the mockery inheritance problem.

$dependencyMock = $this->getMockBuilder('\Some\Name\Space\Dependency')
    ->disableOriginalConstructor()
    ->getMock();
$testable = new Testable($dependencyMock);

Problem

Lets say I have a class that contains a function that uses type hinting like this: ``` class Testable { function foo (Dependency $dependency) { } } ``` And I want to unit test this class `Testable` using this code: ``` $dependencyMock = $this->getMockBuilder('Dependency') ->disableOriginalConstructor() ->getMock(); $testable = new Testable($dependencyMock); ``` If I use PHPUnit to create a stub of $dependency and then try to call the function `foo` using this mock (like above), I will get a fatal error that says: Argument 1 passed to function foo() must be an instance of Dependency, instance of Mock_Foo given How can I unit test this function with PHPUnit and still stub `$dependency`?

Original source