vendredi 6 mai 2016

Stubbing a method called in the constructor of an abstract class

I have the same problem as described here, but because I'm testing an abstract class, I can't invoke the __construct() method (like you see in my test-code). Is there a way I can solve this without refactoring my class?

Class to test:

abstract class Order
{
    public function __construct( $orderId, User $user )
    {
        $this->id = $this->findOrderId( $user->getId(), $orderId );

        if ($this->id !== false) {
            $this->setOrderData();
        }
    }

    abstract protected function findOrderId( $userId, $orderIdToSearch );

    private function setOrderData()
    {
        ...
    }
}

Test code:

class OrderTest extends PHPUnit_Framework_TestCase
{
    public function testCreateOrder() {
        $order = $this->getMockBuilder( 'Order\Order' )
                ->setMethods( [ 'findOrderId' ] )
                ->disableOriginalConstructor()
                ->getMockForAbstractClass();
        $order->expects( $this->once() )
                ->method( 'findOrderId' )
                ->willReturn( 123 );

        ...
    }
}

Aucun commentaire:

Enregistrer un commentaire