简体   繁体   English

在symfony 1.4中使用mockery进行PHP单元测试

[英]PHP Unit testing with mockery in symfony 1.4

I'm trying to do unit testing in symfony 1.4 (actually it's 1.5.3 ( https://github.com/LExpress/symfony1 )) with phpunit and mockery. 我正在尝试使用phpunit和mockery在symfony 1.4中进行单元测试(实际上它是1.5.3( https://github.com/LExpress/symfony1 ))。 Is there a way to load all files of symfony and then, if needed, create mock object from a loaded class? 有没有办法加载symfony的所有文件,然后,如果需要,从加载的类创建模拟对象? The error message is: "Could not load mock {ClassName}, class already exists", which is pretty self explanatory, but I would like to use some of the original methods, not just the ones I've mocked. 错误消息是:“无法加载模拟{ClassName},类已经存在”,这是非常自我解释,但我想使用一些原始方法,而不仅仅是我嘲笑的方法。 Is there a way to do that? 有没有办法做到这一点?

For example: 例如:

public funtion testTest() {
    $mock = Mockery::mock("alias:Site")->shouldReceive('getCurrent')->shouldReturn(3);
    $this->assertEquals(3, Project::test());
}

public static function test() {
    return Site::getCurrent();
}

If I include only the Project class, it works, but if all project files are included I get the error message. 如果我只包含Project类,它可以工作,但如果包含所有项目文件,我会收到错误消息。 But what if the test() function uses other methods of the Site object, which I don't want to mock? 但是如果test()函数使用Site对象的其他方法,我不想模拟呢?

If you would like to use some of the original methods of the class used to produce the mock object via Mockery, there is the makePartial function that can help us. 如果您想使用通过Mockery生成模拟对象的类的一些原始方法,那么makePartial函数可以帮助我们。 This is called Partial Test Doubles. 这称为部分测试双打。

class Site {
    function getUrl() { return 'https://stackoverflow.com'; }
    function getCurrent() { return $this->getUrl(); }
}

$foo = mock(Testable::class)->makePartial();
$foo->getUrl(); // 'https://stackoverflow.com';
$foo->getCurrent(); // 'https://stackoverflow.com'

$foo->shouldReceive('getUrl')->andReturn('http://test.com');
$foo->getCurrent(); // 'http://test.com'

To know more about the Partial Test Doubles here is the official documentation link http://docs.mockery.io/en/latest/reference/creating_test_doubles.html#partial-test-doubles 要了解有关Partial Test Doubles的更多信息,请访问官方文档链接http://docs.mockery.io/en/latest/reference/creating_test_doubles.html#partial-test-doubles

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM