4

This is my unit test in my custom module:

namespace Star\Trek\Test\Unit\Model;

class BeyondTest extends \PHPUnit\Framework\TestCase
{

}

How can I get my Magento 2 base URL in there?

  • 1
    Sounds like you need an integration test, not a unit test. – Shawn Abramson Jul 1 '19 at 3:35
3
+50
namespace Star\Trek\Test\Unit\Model;
class BeyondTest extends \PHPUnit\Framework\TestCase
{
        protected $_storeManager;

    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
    )
    {        
        $this->_storeManager = $storeManager;
    }


    /**
     * Prining URLs using StoreManagerInterface
     */
    public function getStoreManagerData()
    {            
        echo $this->_storeManager->getStore()->getBaseUrl() . '<br />';        
        echo $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB) . '<br />';
        echo $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_DIRECT_LINK) . '<br />';
        echo $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . '<br />';
        echo $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_STATIC) . '<br />';
    }

}
3

I think you have to look into the core Magento unit test code how they use and get base URL.

I am not sure about this is what I shared is exactly you want, but I think it will help you.

Look into the Magento core test module.

vendor/magento/module-cms/Test/Unit/Helper/Wysiwyg/ImagesTest.php

Find the function public function testGetBaseUrl() inside this function they get base URL $this->imagesHelper->getBaseUrl(); using imageHelper they are use protected variable protected $imagesHelper; by class \Magento\Cms\Helper\Wysiwyg\Images


UPDATE:

There is one anoter example of to get base URL using storeRepository look into the core module.

vendor/magento/magento2-base/dev/tests/integration/testsuite/Magento/UrlRewrite/Model/StoreSwitcher/RewriteUrlTest.php

See the public function testSwitchToNonExistingPage() they are get store using object manager using $storeRepository = $this->objectManager->create(\Magento\Store\Api\StoreRepositoryInterface::class); pass the storecode using $toStore = $storeRepository->get($toStoreCode); if you wan to get URL store specific.and finally get URL using $toStore->getBaseUrl();

I think it will help to solve out your issue.

  • 1
    I agree with this answer. So far anything I've seen uses objectManager. – Dominic Xigen Jul 6 '19 at 19:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.