I'm testing php code with phpunit and I have a problem:
I'm testing class:
class ClassName
{
public function MethodName()
{
// something
$objectName = new Object();
$variableName = $objectName->execute();
// something
}
}
I want create mock of Object. I do not want call real method execute(). I dont know how do this with phpunit. I know dependency injection, but IMHO this case is not solved with dependency injection.
Thanks you for answers. I'm sorry for my english.
Actually, this case could be solved with depency injection. Lets say you are not instantiating Object inside MethodName, but injecting it. Whether through contructor, setter, or method does not matter that much for the principle.
class ClassName
{
public function MethodName(Object $objectName)
{
// something
$variableName = $objectName->execute();
// something
}
}
Because you now dont instaniate the object inside the method you want to test, you can pass it a mock when you want to test it.
public function testMethodName(){
$mock = $this->getMockBuilder('Object')->getMock();
$className = new ClassName;
$result = $className->MethodName($mock);
$this->assertTrue($result);
}
I did not run this testmethod, but I think it illustrates the point of depency injection for testability.
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