Search code examples
phpunit-testingzend-frameworkphpunitzend-framework2

How do I alter my unit test to utilise mocks within the setUp function?


I have a relatively basic phpunit test that contains 1 setUp function, and 2 tests - I am still learning phpunit so forgive my ignorance :) Note - I am using the Zend 2 Framework.

I would like the following phpunit test to use mocks but I am unsure how this would work?

<?php

namespace AcmeTest\MetricsClient\Zend;

use Acme\MetricsClient\NullMetricsClient;
use Acme\MetricsClient\Zend\NullMetricsClientFactory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceManager;

class NullMetricsClientFactoryTest extends \PHPUnit_Framework_TestCase
{
    private $serviceManager;
    private $factory;

    protected function setUp()
    {
        $this->factory        = new NullMetricsClientFactory();
        $this->serviceManager = new ServiceManager();
    }

    public function testIsZf2Factory()
    {
        $this->assertInstanceOf(FactoryInterface::class, $this->factory);
    }

    public function testCreatesNullMetricsClientService()
    {
        $nullClient = $this->factory->createService($this->serviceManager);
        $this->assertInstanceOf(NullMetricsClient::class, $nullClient);
    }
}

Solution

  • Use PHPUnit's MockBuilder

    Here's a rough example using your code:

    <?php
    
    namespace AcmeTest\MetricsClient\Zend;
    
    use Acme\MetricsClient\NullMetricsClient;
    use Acme\MetricsClient\Zend\NullMetricsClientFactory;
    use PHPUnit\Framework\MockObject\MockObject;
    use PHPUnit\Framework\TestCase;
    use Zend\ServiceManager\FactoryInterface;
    use Zend\ServiceManager\ServiceManager;
    
    class NullMetricsClientFactoryTest extends TestCase
    {
        private $serviceManager;
    
        private $factory;
    
        protected function setUp()
        {
            $this->factory = $this->getMockBuilder(NullMetricsClientFactory::class)
                ->disableOriginalConstructor()
                ->getMock();
    
            $this->serviceManager = $this->getMockBuilder(ServiceManager::class)
                ->disableOriginalConstructor()
                ->getMock();
        }
    
        public function testIsZf2Factory()
        {
            $this->assertInstanceOf(FactoryInterface::class, $this->factory);
        }
    
        public function testCreatesNullMetricsClientService()
        {
            $nullClient = $this->factory->createService($this->serviceManager);
            $this->assertInstanceOf(NullMetricsClient::class, $nullClient);
        }
    }