有没有更好的方法来编写这个测试?

时间:2013-08-15 22:25:50

标签: laravel phpunit laravel-4 mockery

我对使用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);
}

Item.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));
    }
}

Category.php *

class Category extends Eloquent {

    public function getParentAttribute() {
        return $this->belongsTo('Category','parent_id');
    }

}

1 个答案:

答案 0 :(得分:1)

我不认为这太糟糕了。

测试永远不会“破坏” - 因为如果确实如此,那意味着你的方法首先崩溃了。这是进行测试的全部原因。

如果您需要更改方法,请先写一个新测试(即测试驱动开发)。

你可以考虑阅读Jeffery Way eBook on testing with Laravel 4 - 它值得每一分钱。