【发布时间】:2015-04-04 05:57:29
【问题描述】:
我有两个类,我想通过 PHPUnit 测试它。 但是我在嘲笑这些东西时做错了一些事情。我想改变一个由第一类调用的方法。
class One {
private $someVar = null;
private $abc = null;
public function Start() {
if ( null == $this->someVar) {
$abc = (bool)$this->Helper();
}
return $abc;
}
public function Helper() {
return new Two();
}
}
Class Two {
public function Check($whateverwhynot) {
return 1;
}
}
Class testOne extends PHPUnit_Framework_TestCase {
public function testStart() {
$mockedService = $this
->getMockBuilder(
'Two',
array('Check')
)
->getMock();
$mockedService
->expects($this->once())
->method('Check')
->with('13')
->will($this->returnValue(true));
$mock = $this
->getMockBuilder(
'One',
array('Helper'))
->disableOriginalConstructor()
->getMock();
$mock
->expects($this->once())
->method('Helper')
->will($this->returnValue($mockedService));
$result = $mock->Start();
$this->assertFalse($result);
}
}
结果是$result 是NULL,而不是'true'
如果我不使用断言行,我会收到一条错误消息:
F
Time: 0 seconds, Memory: 13.00Mb
There was 1 failure:
1) testOne::testStart
Expectation failed for method name is equal to <string:Check> when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.
想法?
更新 - 环境:PHP 5.4.3x,PHPUnit 3.7.19 - 重要的一点:不能修改原来的类(一类和二类)
【问题讨论】:
-
PHPUnit 用于依赖注入。您需要将模拟的 Two 类注入 One。另外你没有正确使用 getMockBuilder 方法的参数。
-
getMockBuilder 在哪里使用不好?如何将第二个模拟类注入第一个模拟类?我没有找到任何示例或文档或任何相关内容,您可以删除链接或其他内容吗?
标签: php dependency-injection mocking phpunit unit-testing