等价于SimpleTest“部分模拟"在PHPUnit中? [英] Equivalent of SimpleTest "partial mocks" in PHPUnit?

查看:81
本文介绍了等价于SimpleTest“部分模拟"在PHPUnit中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一堆测试从SimpleTest迁移到PHPUnit,我想知道SimpleTest的部分模拟.

I'm trying to migrate a bunch of tests from SimpleTest to PHPUnit and I was wondering if there is an equivalent for SimpleTest's partial mocks.

更新:我似乎在文档中找不到任何表明该功能可用的东西,但是在我看来,我只能使用一个子类.这是一个好主意还是一个坏主意?

Update: I can't seem to find anything in the docs which suggests that this feature is available, but it occurred to me that I could just use a subclass. Is this a good or bad idea?

class StuffDoer {
    protected function doesLongRunningThing() {
        sleep(10);
        return "stuff";
    }
    public function doStuff() {
        return $this->doesLongRunningThing();
    }
}
class StuffDoerTest {
    protected function doesLongRunningThing() {
        return "test stuff";
    }
}
class StuffDoerTestCase extends PHPUnit_Framework_TestCase {
    public function testStuffDoer() {
        $sd = new StuffDoerTest();
        $result = $sd->doStuff();
        $this->assertEquals($result, "test stuff");
    }
}

推荐答案

通过阅读链接的页面,SimpleTest部分模拟似乎是仅覆盖某些方法的模拟.如果这是正确的,则可以通过普通的PHPUnit模拟来处理该功能.

From reading the linked page, a SimpleTest partial mock seems to be a mock where only some of the methods are overridden. If this is correct, that functionality is handled by a normal PHPUnit mock.

PHPUnit_Framework_TestCase内,您使用

$mock = $this->getMock('Class_To_Mock');

将创建一个模拟实例,其中所有方法均不执行任何操作并返回null.如果只想覆盖某些方法,则getMock的第二个参数是要覆盖的方法数组.

Which creates an mock instance where all methods do nothing and return null. If you want to only override some of the methods, the second parameter to getMock is an array of methods to override.

$mock = $this->getMock('Class_To_Mock', array('insert', 'update'));

将创建一个Class_To_Mock的模拟实例,并删除insertupdate函数,以准备指定其返回值.

will create an mock instance of Class_To_Mock with the insert and update functions removed, ready for their return values to be specified.

此信息位于 phpunit文档中.

注意此答案显示了更多适用于PHPUnit版本的最新代码示例5.4

Note, this answer shows more up to date code examples, for PHPUnit versions starting 5.4

这篇关于等价于SimpleTest“部分模拟"在PHPUnit中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆