createMock vs createPartialMock vs createConfiguredMock (PHP unit methods in Magento 2)

magento.stackexchange https://magento.stackexchange.com/questions/324910

  •  15-04-2021
  •  | 
  •  

سؤال

What is the difference between createMock, createPartialMock and createConfiguredMock methods of PHPUnit\Framework\TestCase class in Magento 2?

هل كانت مفيدة؟

المحلول

createMock:

createMock(string $originalClassName)

It uses the getMockBuilder method to create a test double for the specified class. It disables the constructor of the original class (you will almost always want to do that)

createPartialMock:

createPartialMock(string $originalClassName, array $methods)

The createPartialMock method is very similar to createMock but it lets you specify an array with a subset of methods to be mocked (createMock doesn't mock any method by default). This is specially useful in Magento 2 when mocking factories, since you will need the create method of the factory to be mocked.

Example:

$this->priceFactoryMock = $this->createPartialMock(
    \Magento\ProductAlert\Model\PriceFactory::class,
    ['create']
);
$this->priceFactoryMock->expects(
    $this->once()
)->method('create')->willReturn(
    $priceMock
);

createConfiguredMock:

createConfiguredMock(string $originalClassName, array $configuration)

Similar to createMock but accepts a configuration array with a list of methods and their corresponding return values. Internally, it sets the willReturn value for the methods specified. An example use in Magento 2 would be:

$this->resourceConnectionMock = $this->createConfiguredMock(
    ResourceConnection::class,
    [
        'getConnection' => $this->adapterMock,
        'getTableName'  => self::PREFIXED_TABLE_MEDIA_GALLERY_ASSET
    ]
);

Here, besides creating the mock for the Magento\Framework\App\ResourceConnection class, we are also specifying the return values of the getConnection and getTableName methods inside that class. You would obtain the same result if you first create the mock with createMock and then use willReturn like this:

$this->resourceConnectionMock = $this->createMock(ResourceConnection::class);
$this->resourceConnectionMock->method('getConnection')->willReturn($this->adapterMock);
$this->resourceConnectionMock->method('getTableName')->willReturn(self::PREFIXED_TABLE_MEDIA_GALLERY_ASSET);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى magento.stackexchange
scroll top