Tuesday, July 7, 2015

Mocking PHP functions in PHPUnit test

It relies on using namespaces. Call to PHP function must be in the form time() and not \time().

Class to test(Example.php):
<?php
namespace Example;
class Example {
    public function doSomething()
    {
         return time();
    }
}


Test class(ExampleTest.php):
<?php
namespace Example {
    function time()
    {
        return 5;
    }
}
namespace ExampleTest {
    use Example\Example;

    class ExampleTest extends \PHPUnit_Framework_TestCase {
        protected $sut;

        public function setUp()
        {
             $this->sut = new Example();
        }

        public function testDoSomething()
        {
             $this->assertSame(5, $this->sut->doSomething());
        }
    }
}


Note: Auto loading of classes is omitted.

No comments:

Post a Comment