luk*_*888 5 php phpunit mocking
我正在使用phpunit测试php代码,我遇到了一个问题:
我正在测试课程:
class ClassName
{
public function MethodName()
{
// something
$objectName = new Object();
$variableName = $objectName->execute();
// something
}
}
Run Code Online (Sandbox Code Playgroud)
我想创建对象的模拟.我不想调用实际方法execute().我不知道怎么用phpunit.我知道依赖注入,但恕我直言这种情况并没有通过依赖注入来解决.
谢谢你的回答.我很抱歉我的英语.
实际上,这种情况可以通过依赖注入来解决.假设您没有在MethodName中实例化Object,而是注入它.无论是通过构造函数,设置器还是方法,对于该原理而言都无关紧要.
class ClassName
{
public function MethodName(Object $objectName)
{
// something
$variableName = $objectName->execute();
// something
}
}
Run Code Online (Sandbox Code Playgroud)
因为您现在不想在要测试的方法中实例化对象,所以当您想要测试它时,可以将它传递给它.
public function testMethodName(){
$mock = $this->getMockBuilder('Object')->getMock();
$className = new ClassName;
$result = $className->MethodName($mock);
$this->assertTrue($result);
}
Run Code Online (Sandbox Code Playgroud)
我没有运行这种测试方法,但我认为它说明了可测性的依赖注入点.