1

Possible Duplicate:
PHPUnit Mock Objects and Static Methods
unit testing and Static methods

I'm using PHPUnit 3.6.10 and I can't seem to find a good example of mocking static methods in the documentation. Specifically, I have a class A with method a() -- call it A->a() -- which calls B::b() which I need to mock the return value of.

class A {
    function a() {
        return B::b();
    }
}

class B {
    static function b() {
        return 5;
    }
}

The test function for a() should look like below:

class A_Test {
    function test_a() {
        // what should the code look like here?
    }
}

Since we're purely testing that A->a() returns B::b(), we're not concerned with how B::b() works, so we can mock the return value of B::b() (say, to return 'foo') and check that 'foo' is returned when we call A->a(). How can this be done?

7
  • Is there a way to write the test without having to refactor the code at all? Commented Aug 28, 2012 at 7:05
  • you dont have to refactor anything. you just set the expectation for B with staticExpects. Commented Aug 28, 2012 at 7:08
  • 2
    Static method calls are inherently difficult to test, and they're often a code smell that you've got a tight coupling between the class under test and the class that's providing the static method. For these reasons, statics are often frowned upon these days. Commented Aug 28, 2012 at 7:16
  • To use staticExpects here, A::a would have to call MockB::b. Static expectations are designed for when a method calls a static method on its own class, e.g., self::foo. Changing that call to static::foo allows you to mock it. Commented Aug 28, 2012 at 8:06
  • @DavidHarkness So you are saying that it is impossible to mock the call to B::b() from A->a()? Is there a way to test A->a() then, without having to refactor the code? If not, what solutions do you propose? Commented Aug 28, 2012 at 23:06

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.