How do I get PHPUnit to substitute a class in my test method?
I have a class I want to test. Here is the code:开发者_运维知识库
class MyClass
{
    function functionToTest() {
        $class = new Example();
}
In PHPUnit, can I use mocks/stubs to substitute for the Example class?
In my test method:
class MyClassTest extends PHPUnit_Framework_TestCase {
    function testFunctionTest() {
        $testClass = new MyClass();
        $result = $testClass->functionTest();
    }
}
So instead of using the actual "Example" class, can PHPUnit intervene here and use the mock to represent "new Example()" ?
The best solution would be to inject an Example instance into functionToTest() method:
function functionToTest( Example $class )
Then you'll be able to mock it in your unit tests:
function testFunctionTest() {
    $testClass = new MyClass();
    $class = $this->getMock( 'Example' );
    $result = $testClass->functionTest( $class );
}
But if this approach is for some reason not an option for you, try using set_new_overload() function provided by the test_helpers extensions. See more info in Sebastian Bergmann's blog.
 加载中,请稍侯......
      
精彩评论