我正在为这样一个实体编写单元测试:
class Image
{
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $path;
/**
* @return string
*/
public function getUrl()
{
return $this->getPath() . $this->getName();
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getPath()
{
return $this->path;
}
}
可以看到,getUrl()
方法返回一个由path
和name
组成的字符串。
下面是测试它的代码:
class ImageTest extends 'PHPUnit_Framework_TestCase
{
/**
* Tests all get and set methods
*/
public function testImage()
{
$resource = new Image();
$test = array(
'name' => 'testName.jpg',
// Set this without the ending slash (/)
'path' => 'path/to/image',
);
$test['url'] = $test['path'] . $test['name'];
$this->assertEquals($test['name'], $resource->getName());
// Check that, when set, a slash (/) is added at the end of the Path
$this->assertEquals($test['path'] . '/', $resource->getPath());
$this->assertEquals($test['url'], $resource->getUrl());
}
}
如您所见,首先必须创建array
,然后才可能设置$test['url']
。
在这一点上,好奇心因为我写的,而不是这样的东西:
$test = array(
'name' => 'testName.jpg',
'path' => 'path/to/image',
'url' => $test['path'] . '/' . $test['name']
);
但是这个语法返回这个错误:
有1个错误:
1) Tests'Entity'ImageTest::testImage测试
也许Objects
有类似self
的语句吗?
No。直到$test = array(...);
命令完成后才定义数组。
$test = array(
'name' => 'testName.jpg',
'path' => 'path/to/image',
);
$test['url'] = $test['path'] . '/' . $test['name'];
它看起来不像你想做的那样好,但这是正确的方法。