简体   繁体   中英

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);
    }
}

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM