2

As best I can tell, the 'mockBuilder' function is exactly what I want, and based on other examples, should work.

Am I missing something? How can I stub out the global craft() object?

under test:

<?php

namespace Craft;


class JobsVariable
{

     // Grab all Jobss
     public function jobs()
      {
            return craft();
      }
 }

test file:

    <?php

    namespace Craft;

    require_once 'www/craftcms/plugins/jobs/variables/JobsVariable.php';


    class JobsVariableTest extends \PHPUnit_Framework_TestCase
    {



        public function testJobs()
        {


            $craft = $this->getMockBuilder('\\Craft')
                ->disableOriginalConstructor()
                ->setMethods(array('craft'))
                ->getMock();


            $craft->method('craft')->willReturn('xxx');


            $jobs = new \Craft\JobsVariable();
            $this->assertEquals('xxx', $jobs->jobs());

        }
    }

output:

PHP Fatal error:  Call to undefined function Craft\craft()
1
  • This is a rather extensive self-conversation @nullsteph! Would you kindly accept whichever of your answers you feel is best?
    – Matt Stein
    Commented May 9, 2017 at 23:57

2 Answers 2

1

Whew...this seems to do the trick! Hopefully this is an appropriate way to handle things.

I created a new Craft class file in the 'tests' dir. There I can stub out any \Craft\craft() methods the class under test depends on.

stub class \tests\Craft

<?php

class Craft {

    public function __construct()
    {
    }

    public function jobs()
    {
        return 'xxx';
    }
    public function getJobs()
    {
        return 'xxx';
    }

    public function craft()
    {
        return $this;
    }
}

in the test class

<?php

namespace Craft;

require_once '/www/craftcms/plugins/jobs/variables/JobsVariable.php';
require_once '/www/craftcms/tests/Craft.php';


class JobsVariableTest extends \PHPUnit_Framework_TestCase
{

    public function testJobs()
    {
        $jobs = new \Craft\JobsVariable();
        $this->assertEquals('xxx', $jobs->jobs());

    }
}
function craft()
{
    return new \Craft;
}

allows me to test this function...

public function jobs()
{
    return craft()->jobs();
}
1

...and because the actual test method to get mocked looks like this: craft()->jobs->getJobs()

I can mock this up by adding a class to my stubbed out \test\Craft class;

<?php

class Craft {

    public $jobs;

    public function __construct()
    {
        $this->jobs = new Jobs;
    }
}


class Jobs{

    public function __construct(){
        var_dump('new jobs');
    }


    public function getJobs(){
        return 'xxx';
    }
}

Now I can return dummy test data ('xxx'), instead of letting the code make network requests for real data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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