How to unit test functions that use type hinting

user3009816 picture user3009816 · Dec 7, 2013 · Viewed 12.9k times · Source

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?

Answer

Shakil picture Shakil · Dec 10, 2013

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);