public function ProductTest::testVariationMethods in Commerce Core 8.2
@covers ::getVariationIds @covers ::getVariations @covers ::setVariations @covers ::hasVariations @covers ::addVariation @covers ::removeVariation @covers ::hasVariation @covers ::getDefaultVariation
File
- modules/
product/ tests/ src/ Kernel/ Entity/ ProductTest.php, line 123
Class
- ProductTest
- Tests the Product entity.
Namespace
Drupal\Tests\commerce_product\Kernel\EntityCode
public function testVariationMethods() {
$variation1 = ProductVariation::create([
'type' => 'default',
'sku' => strtolower($this
->randomMachineName()),
'title' => $this
->randomString(),
'status' => 0,
]);
$variation1
->save();
$variation2 = ProductVariation::create([
'type' => 'default',
'sku' => strtolower($this
->randomMachineName()),
'title' => $this
->randomString(),
'status' => 1,
]);
$variation2
->save();
$product = Product::create([
'type' => 'default',
]);
$product
->save();
// An initially saved variation won't be the same as the loaded one.
$variation1 = $this
->reloadEntity($variation1);
$variation2 = $this
->reloadEntity($variation2);
$variations = [
$variation1,
$variation2,
];
$this
->assertEmpty($product
->hasVariations());
$product
->setVariations($variations);
$this
->assertNotEmpty($product
->hasVariations());
$variations_match = $variations == $product
->getVariations();
$this
->assertNotEmpty($variations_match);
$variation_ids = [
$variation1
->id(),
$variation2
->id(),
];
$variation_ids_match = $variation_ids == $product
->getVariationIds();
$this
->assertNotEmpty($variation_ids_match);
$this
->assertNotEmpty($product
->hasVariation($variation1));
$product
->removeVariation($variation1);
$this
->assertEmpty($product
->hasVariation($variation1));
$product
->addVariation($variation1);
$this
->assertNotEmpty($product
->hasVariation($variation1));
$this
->assertEquals($product
->getDefaultVariation(), $variation2);
$this
->assertEquals($variation2, $product
->get('default_variation')->entity);
$this
->assertNotEquals($product
->getDefaultVariation(), $variation1);
// Confirm that postSave() sets the product_id on each variation.
$product
->save();
/** @var \Drupal\commerce_product\Entity\ProductVariationInterface $variation1 */
$variation1 = $this
->reloadEntity($variation1);
/** @var \Drupal\commerce_product\Entity\ProductVariationInterface $variation2 */
$variation2 = $this
->reloadEntity($variation2);
$this
->assertEquals($product
->id(), $variation1
->getProductId());
$this
->assertEquals($product
->id(), $variation2
->getProductId());
// Confirm that postDelete() deletes the variations.
$product
->delete();
$variation1 = $this
->reloadEntity($variation1);
/** @var \Drupal\commerce_product\Entity\ProductVariationInterface $variation2 */
$variation2 = $this
->reloadEntity($variation2);
$this
->assertNull($variation1);
$this
->assertNull($variation2);
}