

1.ユニットテストとは?
基本的にユニットテストとは、ソフトウェアテストの一部として知られており、ソフトウェアの小さな単位ごとにテストを行います。このテストの主な目的は、ソフトウェアコードが期待通りに動作するかどうかを検証することです。ユニットテストは、アプリケーションの開発過程で行われます。
2.なぜユニットテストが必要なのか?
ユニットテストは、主に制作時に発生するバグやエラーの数を減らすために行われます。正確なユニットテストは、Magentoのプロジェクトに最も近い開発者から実施され、ユニットテストの助けを借りて、他のすべての開発者がコードをより正確に理解し、学ぶ機会を得ることができます。
3.Magento 2 でユニットテストファイルを作成する手順
3.1.ステップ1
以下のパスに「 Unittest.php 」ファイルを作成し、コードを追加します。
app\code\Vendor\Extension\Model\
<?php
namespace Vendor\Extension\Model;
class Unittest
{
/**
* this function will perform the addition of two numbers
*
* @param int $no1
* @param int $no2
* @return int
*/
Public function additiondata($no1 ,$no2)
{
return $no1 + $no2;
}
}
3.2.ステップ 2
以下のパスにUnittest.phpを作成し、コードを追加します。
app\code\Vendor\Extension\Test\Unit\Model\
<?php
namespace Vendor\Extension\Test\Unit\Model;
class Unittest extends \PHPUnit\Framework\TestCase
{
public function setUp() : void
{
$this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
$this->_calculator = $this->_objectManager->getObject("Vendor\Extension\Model\Unittest");
}
/**
* this function will perform the addition of two numbers
*
* @param int $no1
* @param int $no2
* @return int
*/
public function testcaseAddition(): void
{
$this->_actulResult = $this->_calculator->additiondata(7,7); // call additiondata method from model file
$this->_desiredResult = 14; // actual result compare set
$this->assertEquals($this->_desiredResult, $this->_actulResult); /* check test case match or not if true the give ok message otherwise give error */
}
}
上記のコードを追加した後、Magento 2 のルートディレクトリのターミナルで以下のコマンドを実行します。
php vendor/phpunit/phpunit/phpunit -c dev/tests/unit/phpunit.xml.dist
app/code/Vendor/Extension/Test/Unit/Model/Unittest.php
最後に
以上の説明で、Magento 2 でユニットテストファイルを作成することができたと思います。万が一、ユニットファイルの作成中にエラーが発生した場合は、以下のコメント欄で私に質問してください。
以上。