Question

I'm fairly new to unit testing with Laravel and Mockery and I wrote the following test. It passes and seems to work. However, I think that it's probably could be written in a better way. It seems that the test is more likely to break than the implementation. Are there better ways to do this?

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');
    }

}
Was it helpful?

Solution

I dont think it is too bad.

The test should never "break" - because if it does, that means your method broke first. That is the whole reason to have tests.

If you need to change your method, then write a new test first (i.e. Test Driven Development).

You might consider reading Jeffery Way eBook on testing with Laravel 4 - its worth every cent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top