我对使用 Laravel 和 Mockery 进行单元测试还很陌生,我编写了以下测试。它通过并且似乎有效。但是,我认为它可能可以以更好的方式编写。似乎测试比实现更容易出错。有没有更好的方法来做到这一点?
ItemModelTest.php
...
public function mock($class)
{
$mock = Mockery::mock($class);
$this->app->instance($class, $mock);
return $mock;
}
// It seems like this test might be more likely to break then the method itself.
public function testCatTree() {
$categoryMock = $this->mock("Category");
$categoryMock->shouldReceive("getAttribute")->with("name")->times(3)
->andReturn("self","parent1","parent2");
$categoryMock->shouldReceive("getAttribute")->with("parent")->times(3)
->andReturn($categoryMock, $categoryMock, null);
$i = new Item;
$i->setAttribute("category",$categoryMock);
$tree = $i->catTree;
Should::equal("parent2 > parent1 > self", $tree);
}
项目.php
class Item extends Eloquent {
public function category() {
return $this->belongsTo("Category");
}
public function getCatTreeAttribute() {
$category = $this->category;
if(!$category) return "";
$tree = array($category->name);
$parent = $category->parent;
while($parent) {
$tree[] = $parent->name;
$parent = $parent->parent;
}
return implode(" > ", array_reverse($tree));
}
}
类别.php*
class Category extends Eloquent {
public function getParentAttribute() {
return $this->belongsTo('Category','parent_id');
}
}