在 php 父 class 中模拟或存根方法
Mock or Stub a method in a php parent class
我正在 phpunit 中测试 class,但我不是在嘲笑它,class 是这样的:
class MyClass extends ParentClass
{
public function doSomething($param)
{
//do some stuff
$someValue = $this->anotherMethod(); //this method is defined in the parent class
//do some other stuff with $someValue
return $finalValue;
}
}
在测试中class我是这样做的
public function testDoSomething($param)
{
$myclass = new MyClass();
//here I need to control the value of $someValue, as it affects the final value returned
$res = $myClass->doSomething();
$this->assertEqual('sonething', res);
}
所以我的问题是如何控制从 anotherMethod 方法返回的值?我更喜欢模拟它,这样它就不会调用其中的其他方法
您可以部分模拟您的 class 并检测您不想测试的方法,如下例所示:
public function testDoSomething()
{
/** @var \App\Models\MyClass $classUnderTest */
$classUnderTest = $this->getMockBuilder(\App\Models\MyClass::class)
->onlyMethods(['anotherMethod'])
->getMock();
$classUnderTest->expects($this->once())
->method('anotherMethod')
->willReturn('mocked-value');
$this->assertEquals("from-test mocked-value", $classUnderTest->doSomething("from-test"));
}
来源如下:
父类
class ParentClass
{
public function anotherMethod() {
return "parent-value";
}
}
和MyClass
class MyClass extends ParentClass
{
public function doSomething($param)
{
//do some stuff
$someValue = $this->anotherMethod(); //this method is defined in the parent class
//do some other stuff with $someValue
$finalValue = $param . ' '. $someValue;
return $finalValue;
}
}
我正在 phpunit 中测试 class,但我不是在嘲笑它,class 是这样的:
class MyClass extends ParentClass
{
public function doSomething($param)
{
//do some stuff
$someValue = $this->anotherMethod(); //this method is defined in the parent class
//do some other stuff with $someValue
return $finalValue;
}
}
在测试中class我是这样做的
public function testDoSomething($param)
{
$myclass = new MyClass();
//here I need to control the value of $someValue, as it affects the final value returned
$res = $myClass->doSomething();
$this->assertEqual('sonething', res);
}
所以我的问题是如何控制从 anotherMethod 方法返回的值?我更喜欢模拟它,这样它就不会调用其中的其他方法
您可以部分模拟您的 class 并检测您不想测试的方法,如下例所示:
public function testDoSomething()
{
/** @var \App\Models\MyClass $classUnderTest */
$classUnderTest = $this->getMockBuilder(\App\Models\MyClass::class)
->onlyMethods(['anotherMethod'])
->getMock();
$classUnderTest->expects($this->once())
->method('anotherMethod')
->willReturn('mocked-value');
$this->assertEquals("from-test mocked-value", $classUnderTest->doSomething("from-test"));
}
来源如下:
父类
class ParentClass
{
public function anotherMethod() {
return "parent-value";
}
}
和MyClass
class MyClass extends ParentClass
{
public function doSomething($param)
{
//do some stuff
$someValue = $this->anotherMethod(); //this method is defined in the parent class
//do some other stuff with $someValue
$finalValue = $param . ' '. $someValue;
return $finalValue;
}
}