chukShirley
7/22/2016 - 8:30 PM

Mocking Zend Db Table Gateway

Mocking Zend Db Table Gateway

<?php
namespace Load\Service\Query;

use Load\Infrastructure\Persistence\LoadTable;
use ServiceBus\Query\QueryHandlerInterface;
use Zend\Db\Sql\Predicate\Operator;
use Zend\Db\Sql\Select;

/**
 * Class FetchAllUnpaidLoadsQueryHandler
 * @package Load\Service\Query
 */
class FetchAllUnpaidLoadsQueryHandler implements QueryHandlerInterface
{
    /** @var LoadTable */
    private $loadTable;

    /**
     * FetchAllUnpaidLoadsQueryHandler constructor.
     * @param LoadTable $loadTable
     */
    public function __construct(LoadTable $loadTable)
    {
        $this->loadTable = $loadTable;
    }

    /**
     * @param FetchAllUnpaidLoadsQuery $query
     * @return array
     */
    public function handle($query)
    {
        $select = new Select('SCF030J1');
        $select->columns(
            [
                'id' => 'TLSRN'
            ]
        )->where([
            'TLPAYSTS' => '0',
            new Operator('TLLOAD', Operator::OP_GT, '0')
        ]);
        return $this->loadTable->selectWith($select)->toArray();
    }
}
<?php
namespace LoadTest\Service\Query;

use Load\Service\Query\FetchAllUnpaidLoadsQuery;
use Load\Service\Query\FetchAllUnpaidLoadsQueryHandler;
use PHPUnit_Framework_TestCase;
use Load\Infrastructure\Persistence\LoadTable;

/**
 * Class FetchAllUnpaidLoadsQueryHandlerTest
 * @package LoadTest\Service\Query
 */
class FetchAllUnpaidLoadsQueryHandlerTest extends PHPUnit_Framework_TestCase
{
    private $loadTable;

    public function setUp()
    {
        $this->loadTable = $this->getMockBuilder(LoadTable::class)
                                ->disableOriginalConstructor()
                                ->setMethods(['selectWith'])
                                ->getMock();
    }

    public function testQueryHandlerReturnsQueryResults()
    {
        $data = [
            [
                'id' => '12345',
            ],
            [
                'id' => '12346',
            ]
        ];
        $this->loadTable->method('toArray')->willReturn(
            $data
        );
        $query = new FetchAllUnpaidLoadsQuery();
        $handler = new FetchAllUnpaidLoadsQueryHandler(
            $this->loadTable
        );
        $actual = $handler->handle($query);
        $expected = $data;
        $this->assertEquals($expected, $actual);
    }
}