[英]PHPUnit: How to mock an internally called function by the method under test
In the below example, I want to mock the calling of getBaseValue()
inside the multipliedValue()
. 在下面的例子中,我想嘲弄的呼叫
getBaseValue()
内multipliedValue()
But I cannot figure it out. 但我无法弄清楚。
class Sample
{
function multipliedValue()
{
$value = $this->getBaseValue();
return $value * 2;
}
function getBaseValue()
{
return 2;
}
}
I have used PHPUnit mocking, but it didn't work. 我使用过PHPUnit模拟,但是没有用。 So, I used the following code:
因此,我使用了以下代码:
class SampleTest extends PHPUnit_Framework_TestCase
{
function testMultipliedValueIfBaseValueIsFalse()
{
$mockedObject = $this->getMockBuilder(Sample::class)
->setMethods(['multipliedValue', 'getBaseValue'])
->getMock();
$mockedObject->expects($this->any())
->method("getBaseValue")
->willReturn(false);
$result = $mockedObject->multipliedValue();
$this->assertFalse($result);
}
}
I tried to create a global function, but only force one of the method to return my desired value, the rest just go as they are. 我试图创建一个全局函数,但是仅强制其中一种方法返回我想要的值,其余方法照原样进行。 How should I approach this test?
我应该如何进行这项测试?
The error I am currently getting is for the $this
in the multipliedValue()
method, which treats it as the stubbed object. 我当前遇到的错误是
multipliedValue()
方法中的$this
,将其视为存根对象。
All the methods listed in the ->setMethods()
will be stubbed and return null
by default so if you only want to stub getBaseValue
then do: ->setMethods()
列出的所有方法都将被存根,并且默认情况下返回null
,因此,如果您只想存根getBaseValue
请执行以下操作:
$mockedObject = $this->getMockBuilder(Sample::class)
->setMethods(['getBaseValue'])
->getMock();
$mockedObject->expects($this->any())
->method("getBaseValue")
->willReturn(false);
$result = $mockedObject->multipliedValue();
$this->assertFalse($result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.