Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add constant to a mock in PHPUnit

Is it possible to add a class constant to a mock using PHPUnit?

Here an example:

class SomeTest extends PHPUnit_Framework_TestCase {
    public function setUp() {
        $mock = $this->getMock( 'SomeClass' );
        // Here I'd like to add a constant to $mock; something like
        // $mock::FOOBAR;
    }
}

Does any of you know how can I get this behavious to work?

Thx!

like image 522
ThisIsErico Avatar asked Jun 05 '13 19:06

ThisIsErico


1 Answers

This question has been around a while with no answers, but I ran into this same problem. This does not appear to be possible; however, there's at least one dirty work-around:

In your test file

<?php

class SomeClass {
    const FOOBAR = 'foobar';
}

class SomeTest extends PHPUnit_Framework_TestCase {
    public function setUp() {
        $mock = $this->getMock( 'SomeClass' );
    }
}

// tests

?>

Then, you use your mocked object for mocked functionality, and you use the class constant the same way you would have originally. For example:

// Call a method on mocked object
// (would need to add this method to your mock, of course)
$mock->doSomething();
// Use the constant
$fooBar = SomeClass::FOOBAR;

This is dirty, so I'm sure things could get pretty messed up if you're using some sort of autoloading that tries to load the actual SomeClass class, but this will work "fine" if you're not loading the original SomeClass.

I'm definitely interested to hear other solutions as well as get some feedback on just how dirty this really is.

like image 112
MuffinTheMan Avatar answered Dec 04 '22 10:12

MuffinTheMan