Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test functions that use type hinting

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?

like image 347
user3009816 Avatar asked Dec 07 '13 21:12

user3009816


People also ask

How do you unit test a function?

A typical unit test contains 3 phases: First, it initializes a small piece of an application it wants to test (also known as the system under test, or SUT), then it applies some stimulus to the system under test (usually by calling a method on it), and finally, it observes the resulting behavior.

How many types of methods we can test by using unit testing?

There are 2 types of Unit Testing: Manual, and Automated.

What can be mocked for unit testing?

What is mocking? Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to isolate and focus on the code being tested and not on the behavior or state of external dependencies.


1 Answers

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); 
like image 85
Shakil Avatar answered Oct 15 '22 12:10

Shakil