模拟在方法中间创建的对象

Ric*_*ola 3 php testing phpunit mockery

Class我知道在 a 中间创建 a 实例method是一种不好的做法,因为它使代码难以测试。但我无法重构代码,所以我需要找到一种方法来模拟在测试过程中Object创建的对象。newmethod

使用的框架:PHPUnit, Mockery,WP_Mock

示例:这里我需要模拟get_second_string()类实例中的方法ExternalClass

Class MyClass {

    function methodUnderTest($string) {
        $objToMock = new ExternalClass();
        $second_string = $objToMock->get_second_string();
        $final_string = $string . $second_string;
        return $final_string;
    }
}
Class TestMyClass extends PHPUnit_Framework_TestCase {
    public function setUp() {
    }
    public function tearDown() {
    }

    public function test_methodUnderTest() {
        $externalObject = $this->getMockBuilder('ExternalClass')
                               ->setMethods(['get_second_string'])
                               ->getMock;
        $externalObject->expects($this->once())
                       ->method('get_second_string')
                       ->willReturn(' two');
        $testObj = new MyClass();
        $this->assertEquals('one two', $testObj->methodUnderTest('one');
    }
}
Run Code Online (Sandbox Code Playgroud)

xmi*_*ike 5

如果您确实没有机会重构代码或进行一些适当的集成测试,您可能需要看看https://github.com/php-test-helpers/php-test-helpers#intercepting-object-creationhttps://github.com/krakjoe/uopz/tree/PHP5

尽管如此,我仍然认为你编写的代码从重构中获得的收益比猴子修补的收益要多得多。

此外,重构不需要很重。你至少可以这样做:

class MyClass
{
    private $externalsFactory;

    public function __construct($externalsFactory){
        $this->externalsFactory = $externalsFactory;
    }

    public function methodUnderTest($str){
        $external = $this->externalsFactory->make();
        $second_string = $external->get_second_string();
        $finalString = $str.$second_string;
        return $finalString;
    }
}

class ExternalsFactory
{
    public function make(){
        return new ExternalClass();
    }
}

class ExternalClass
{
    public function get_second_string(){
        return 'some real stuff may be even from database or whatever else it could be';
    }
}

class MyClassTest extends PHPUnit_Framework_TestCase
{
    private $factoryMock;
    private $myClass;

    public function setUp(){
        $this->factoryMock = $this->getMockBuilder('ExternalsFactory')
                                  ->getMock();
        $this->myClass = new MyClass($this->factoryMock);
    }

    public function testMethodUnderTest(){
        $extenalMock = $this->createMock('ExternalClass');
        $extenalMock->method('get_second_string')
                    ->willReturn('second');
        $this->factoryMock->method('make')
                          ->willReturn($extenalMock);
        $this->assertSame('first-and-second', $this->myClass->methodUnderTest('first-and-'));
    }
}
Run Code Online (Sandbox Code Playgroud)