1

I am looking to write basic unit tests for some helper functions that I am working on for a Magento 2 module. I am able to execute my custom module unit tests but I am getting the following error for the first test.

When I execute the tests for my module I get the following error:

Call to a member function getBaseUrl() on null

My Helper code is below: I will be adding quite a few functions to it later and the function its self returns the correct result if I call it else where in my code, I am not able to get the test working.

namespace MyModuleSpace\MyModule\Helper;

use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\StoreManagerInterface;

class Data extends \Magento\Framework\App\Helper\AbstractHelper {

    /**
     * Attribute to hold storeManager Object
     *
     * @var object
     */
    protected  $storeManager;

    /**
     * _construct
     *
     * @param Context $context
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(Context $context, StoreManagerInterface $storeManager) {
        $this->storeManager = $storeManager;
        parent::__construct($context);
    }

    /**
     * No params needed. Returns base site URL.
     *
     * @return string
     */
    public function getBaseURL() {
        return $this->storeManager->getStore()->getBaseUrl();
    }

}

My Unit Test code is

namespace MyModuleSpace\MyModule\Test\Unit\Helper;

//class HelperTest extends \PHPUnit_Framework_TestCase { // not usable as it is not supported
class HelperTest extends \PHPUnit\Framework\TestCase {

    protected $helper;

    /**
     * Sets up the Mock (reflection) objects and properties for tests...
     *
     */
    protected function setUp() {

        $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
        $this->helper = $objectManager->getObject('MyModuleSpace\MyModule\Helper\Data');

    }

    /**
     * Run unit tests for getBaseURL()
     */
    public function testGetBaseURL() {

        $baseUrl = $this->helper->getBaseUrl();

        // Test we are returning a string...
        $this->assertTrue(is_string($baseUrl));

    }


}

I am not sure what I am doing wrong but any help would be appreciated.

  • have you found a solution?, If yes, can you please tell me how. – Sanjay Gohil Jul 2 at 6:55
0

It's bad practise to use ObjecManager, so thats should be improved first. Use your construct to instantiate the classes that you need, including the helper.

  • I agree, I have found a better approach, just got to figure out how to close this question. Followed a bad example from some research I had... – Baber Jan 9 '18 at 14:16
  • To close a question, you can simply accept an answer. – BBQ. Jan 9 '18 at 14:27

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.