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
?
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.
There are 2 types of Unit Testing: Manual, and Automated.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With