Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How mock new object in method - phpunit

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.

like image 624
LukasVitek Avatar asked Jun 04 '13 08:06

LukasVitek


1 Answers

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.

like image 137
qrazi Avatar answered Sep 22 '22 13:09

qrazi