*This is a beginner's question in phpunit so i don't know if it belongs here or not.
I want to test that the var path is correct, but I'm getting Failed asserting that null matches expected '/magento2/var'.
I suppose because I am using a mock for DirectoryList, instead instantiating the class. How does one test it? Should I instantiate DirectoryList? I am having issues with it's constructor...
<?php
namespace Vendor\Module\Cron;
use Magento\Framework\App\Filesystem\DirectoryList;
class Products {
/**
* Retrieve var path
*
* @return string
*/
protected $directory_list;
public function __construct(
DirectoryList $directory_list
)
{
$this->directory_list = $directory_list;
}
/**
* Retrieve var path
*
* @return string
*/
public function getVarFolderPath()
{
return $this->directory_list->getPath('var');
}
}
and my test:
<?php
namespace Vendor\Module\Test\Unit\Model;
use Magento\Framework\App\Filesystem\DirectoryList;
use Vendor\Module\Cron\Products;
class ProductsTest extends \PHPUnit_Framework_TestCase
{
/**
* @var string
*
* dummy var path
*/
const VAR_PATH = '/magento2/var';
/**
* @var Vendor\Module\Cron\Products;
*/
protected $products;
/**
* setup tests
*/
protected function setUp()
{
/** @var \PHPUnit_Framework_MockObject_MockObject|DirectoryList */
$directoryListMock = $this->getMockBuilder(DirectoryList::class)
->disableOriginalConstructor()
->getMock();
$this->products = new Products(
$directoryListMock
);
}
/**
* @test Vendor\Module\Cron\Products::getVarFolderPath()
*/
public function testGetVarFolderPath()
{
$this->assertEquals(self::VAR_PATH, $this->products->getVarFolderPath());
}
}
Update: so Kandy's answer was ok. in unit test you test just that specific class.
1 Answer 1
All mocked methods returns null, so you need describe in your test what getPath method will return:
$directoryListMock->expects($this->any())
->method('getPath')
->with('var')
->willReturn(self::VAR_PATH);
-
and that will actually test anything? to me it looks like I am asserting that
self::VAR_PATH == self::VAR_PATHand not actually testing the result ofgetVarFolderPathClaudiu Creanga– Claudiu Creanga2016年09月04日 20:54:26 +00:00Commented Sep 4, 2016 at 20:54 -
This is because your code does not do anything ;)KAndy– KAndy2016年09月04日 21:15:32 +00:00Commented Sep 4, 2016 at 21:15
-
Sorry but I don't understand what you mean by
the code doesn't do anything. I just want to test that$this->directory_list->getPathalways returns a specific string because my host often changes paths and I have a third party extension that inserts files in the var folder. So I am unsure how to do it. Should I load the object DirectoryList and not make a mock?Claudiu Creanga– Claudiu Creanga2016年09月05日 09:24:25 +00:00Commented Sep 5, 2016 at 9:24