Phpunit 测试一个使用另一个 class 的方法,它被注入到构造函数中
Phpunit test a method that uses another class which is injected in the constructor
说在我的 class 的构造函数中我注入了另一个 class。在我的一种方法中,我的 return 取决于 class。我如何测试 return?
class MyClass {
protected $directoryThatIWant;
public function __construct(
\AnotherClass $directoryThatIWant
)
{
$this->directoryThatIWant = $directoryThatIWant;
}
public function getVarFolderPath()
{
return $this->directoryThatIWant->getPath('var');
}
}
和我的测试 class:
class MyClassTest extends \PHPUnit_Framework_TestCase
{
const PATH = 'my/path/that/I/want';
protected $myClass;
protected function setUp()
{
$directoryThatIWantMock = $this->getMockBuilder(AnotherClass::class)
->disableOriginalConstructor()
->getMock();
$this->myClass = new myClass(
$directoryThatIWantMock
);
}
public function testGetVarFolderPath()
{
$this->assertEquals(self::PATH, $this->myClass->getVarFolderPath());
}
}
来自模拟对象的方法 returns null,所以我不确定如何确保 $this->myClass->getVarFolderPath()
returns 是我想要的值。
谢谢!
您只需要定义模拟对象的行为(如测试双重 phpunit 指南中所述here)。
例如,您可以更改设置方法如下:
protected function setUp()
{
$directoryThatIWantMock = $this->getMockBuilder(AnotherClass::class)
->disableOriginalConstructor()
->getMock();
$directoryThatIWantMock->expects($this->once())
->method('getPath')->with('var')
->willReturn('my/path/that/I/want');
$this->myClass = new myClass(
$directoryThatIWantMock
);
}
希望对您有所帮助
说在我的 class 的构造函数中我注入了另一个 class。在我的一种方法中,我的 return 取决于 class。我如何测试 return?
class MyClass {
protected $directoryThatIWant;
public function __construct(
\AnotherClass $directoryThatIWant
)
{
$this->directoryThatIWant = $directoryThatIWant;
}
public function getVarFolderPath()
{
return $this->directoryThatIWant->getPath('var');
}
}
和我的测试 class:
class MyClassTest extends \PHPUnit_Framework_TestCase
{
const PATH = 'my/path/that/I/want';
protected $myClass;
protected function setUp()
{
$directoryThatIWantMock = $this->getMockBuilder(AnotherClass::class)
->disableOriginalConstructor()
->getMock();
$this->myClass = new myClass(
$directoryThatIWantMock
);
}
public function testGetVarFolderPath()
{
$this->assertEquals(self::PATH, $this->myClass->getVarFolderPath());
}
}
来自模拟对象的方法 returns null,所以我不确定如何确保 $this->myClass->getVarFolderPath()
returns 是我想要的值。
谢谢!
您只需要定义模拟对象的行为(如测试双重 phpunit 指南中所述here)。
例如,您可以更改设置方法如下:
protected function setUp()
{
$directoryThatIWantMock = $this->getMockBuilder(AnotherClass::class)
->disableOriginalConstructor()
->getMock();
$directoryThatIWantMock->expects($this->once())
->method('getPath')->with('var')
->willReturn('my/path/that/I/want');
$this->myClass = new myClass(
$directoryThatIWantMock
);
}
希望对您有所帮助