vendredi 8 mai 2015

Mock Returning Values Via PHPUnit Controller Test Through Zend Service Provider

    $serviceManager = $this->getApplicationServiceLocator();
    $serviceManager->setAllowOverride(true);

    //Order Service

    $realOrderService = $serviceManager->get('order');

    $orderServiceMock = $this
        ->getMockBuilder(get_class($realOrderService))
        ->getMock();


    $serviceManager->setService('order', $orderServiceMock);
    //Order Service Entity
    $realOrderServiceEntity = new \Application\Model\Transaction;
    $orderServiceEntityMock = $this
        ->getMockBuilder(get_class($realOrderServiceEntity))
        ->getMock();

    $orderServiceMock
        ->expects($this->any())
        ->method('getEntity')
        ->will($this->returnValue($orderServiceEntityMock));

    $orderServiceMock
        ->expects($this->any())
        ->method('getIsPaid')
        ->will($this->returnValue(TRUE));

$this->dispatch('/test/create','POST', $data);

In the above code, I am simply getting the class name for the actual object related to the 'order' service provider. I then create a mock of that object.

I then set the service to the instance of the mock so that when the controller references the 'order' service it gets an instance of the mock instead.

Next I create a orderServiceEntityMock based on the \Application\Model\Transaction model.

Then whenever the orderServiceMock getEntity is called I return the mock object.

Then whenever orderServiceMock getIsPaid is called, I want to return true.

The controller:

public function create($data)
{
    //Create the order based on the information sent by the user
    $this->order = $this->getServiceLocator()->get('order');
    $this->order->setCard(new CreditCard($data['order']['billing']));
    $this->order->setAddress(new Address($data['order']['billing']));
    $this->order->setTotal($data['order']['amount']);

    $this->order->processPayment();
    if($this->order->getIsPaid())
    {

Whenever we get down to the last conditional statement, it fails the condition. What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire