Actimele
Actimele

Reputation: 508

PHPUnit mock method used in another class

PHPUnit mock method used in another class? Example:

class Main {
  function makePayment() {
    $pp = new PayPalSOAPSomeClass();
    return $pp->doExpressCheckout();
  }
}

in testing i want test my Main class, and mock doExpressCheckout() method, my not worked code to test:

public function testStub()    {
        $stub = $this->getMock('PayPalSOAPSomeClass');
        $stub->expects($this->any())
             ->method('doExpressCheckout')
             ->will($this->returnValue(false));
        $pp = new Main;
        $this->assertEquals(true, $pp->doExpressCheckout());
    }

Upvotes: 0

Views: 3128

Answers (1)

Steven Scott
Steven Scott

Reputation: 11260

You have a problem testing the Main class. The first problem is that it creates an object internally. You need to modify this class to use dependency injection. Your makePayment() should accept a PayPalSOAPSomeClass object.

function makePayment(PayPalSOAPSomeClass $pp)
{
    return $pp->doExpressCheckout();
}

In your main class, you can modify it to use a constructor dependency injection, or a setter dependency injection, which is better than the makePayment. Then, you reference the internal object.

For instance:

class Main {
    private $svc;

    // Constructor Injection, pass the PayPalSOAPSomeClass object here
    public function __construct($Service = NULL)
    {
        if(! is_null($Service) )
        {
            if($Service instanceof PayPalSOAPSomeClass)
            {
                $this->SetPayPalSOAP($Service);
            }
        }
    }

    function SetPayPalSOAP(PayPalSOAPSomeClass $Service)
    {
        $this->svc = $Service;
    }

    function makePayment() {
        $pp = $this->svc;
        return $pp->doExpressCheckout();
    }
}

Test:

public function testStub()    
{
    $stub = $this->getMock('PayPalSOAPSomeClass');
    $stub->expects($this->any())
        ->method('doExpressCheckout')
        ->will($this->returnValue(false));
    $pp = new Main($stub);
    $this->assertEquals(true, $pp->doExpressCheckout());
}

Upvotes: 3

Related Questions