I've created an API extension that manages gallery easily for our demands and now I wanted to create a unit testing.
For example, one functionality is: give an 'sku' and 'entry' object (with base64 img) and API adds this image on that product.
This is the class I want to test:
<?php
namespace Gsp\ApiExtension\Model;
use Gsp\ApiExtension\Api\SGIMediaInterface;
use Magento\Framework\Api\ImageContentValidatorInterface;
use Magento\Catalog\Api\ProductAttributeMediaGalleryManagementInterface;
use Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Store\Api\StoreRepositoryInterface;
use Magento\Framework\App\ObjectManager;
class SGIMedia implements SGIMediaInterface {
/**
* @var StoreRepositoryInterface $storeRepository
*/
protected $storeRepository;
/**
* @var ProductRepositoryInterface
*/
protected $productRepository;
/**
* @var ImageContentValidatorInterface
*/
protected $contentValidator;
/**
* @var ProductAttributeMediaGalleryManagementInterface
*/
protected $galleryManagement;
/**
* @param StoreRepositoryInterface $storeRepository
* @param ProductAttributeMediaGalleryManagementInterface $galleryManagement
* @param ProductRepositoryInterface $productRepository
* @param ImageContentValidatorInterface $contentValidator
*/
public function __construct(StoreRepositoryInterface $storeRepository, ProductAttributeMediaGalleryManagementInterface $galleryManagement, ProductRepositoryInterface $productRepository, ImageContentValidatorInterface $contentValidator) {
$this->productRepository = $productRepository;
$this->contentValidator = $contentValidator;
$this->galleryManagement = $galleryManagement;
$this->storeRepository = $storeRepository;
}
/**
* @inheritdoc
*/
public function update($skus, ProductAttributeMediaGalleryEntryInterface $entry) {
$sku_array = explode('|', $skus);
foreach ($sku_array as $sku) {
$this->galleryManagement->create($sku, $entry);
}
}
(...)
}
1) I need to mock a product, I've already did that, but then all attributes are NULL, so I would need to set an SKU at least. setData is not working. I'm stuck here.
I did this:
/**
* @var \Magento\Catalog\Model\Product
*/
protected $product;
protected function setUp() {
$this->product = $this->createMock(\Magento\Catalog\Model\Product::class, [], [], '', false);
$this->product->setSku('test');
var_dump($this->product->getSku()); //returns NULL
$this->product->setData('sku', 'test');
var_dump($this->product->getData('sku')); //returns NULL
$this->product->save();
var_dump($this->product->getData('sku')); //returns NULL
}
2) Then I get my model and call my method passing this SKU and a fixed entry as a parameters.
3) Verify the product has this entry.
By the way, I'm very new at unit testing and on Magento too.