【问题标题】:Is there a better way to write this test?有没有更好的方法来编写这个测试?
【发布时间】:2013-08-18 05:54:29
【问题描述】:

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

}

【问题讨论】:

    标签: laravel phpunit laravel-4 mockery


    【解决方案1】:

    我觉得还不错。

    测试不应该“中断” - 因为如果确实如此,则意味着您的方法首先中断。这就是进行测试的全部原因。

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

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

    【讨论】:

    • 我确实读过那本书,我同意它很好。感谢您的反馈!
    猜你喜欢
    • 2019-08-26
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 2023-03-17
    相关资源
    最近更新 更多