laravel测试入门

时间:2013-11-14 22:03:06

标签: php unit-testing laravel refactoring

我正试图掌握测试,并试图测试我正在开发的应用程序。不是TDD所以不是从一个好地方开始,但我认为测试部分构建的应用程序具有工作功能会更容易(错误!)。

我使用Jeffrey Ways生成器创建了许多控制器,这也创建了测试。然后,我修改了这些控制器,使我的应用程序能够完成我需要的操作。我已经设置了phpunit,安装了嘲弄,我已经购买了经过解码的书籍测试并通过它完成了工作。我不能在测试我创建的方法上实现飞跃,即如何测试这个,更重要的是我应该重构什么 - 我需要一个开始......

所以 - 这是我的控制器,用于创建票证簿然后创建每张票的特定方法:

/**
 * Store a newly created resource in storage.
 *
 * @return Response
 */
public function store()

/**
 * Validation rules required:
 * 1. start and end numbers must be unique
 * 2. start number must be less than end number
 * 3. start and end numbers must not exist in ranges created by other books eg overlap
 * 4. must contain date, user
 */
{
    $input = Input::all();
    $validation = Validator::make($input, Book::$rules);

    $input['assigned_date'] = DateTime::createFromFormat( 'd/m/Y', Input::get('assigned_date') )->format( 'Y-m-d' );

    if ($validation->passes())
    {
        $book = $this->book->create($input);

        //once created then create tickets:
        TicketAudit::batchcreate($input['start_number'],$input['end_number'],$book->id);

        return Redirect::route('books.index');
    }

    return Redirect::route('books.create')
        ->withInput()
        ->withErrors($validation)
        ->with('message', 'There were validation errors.');
}

这是我正在进行的测试:

public function testStore()
{
    $input = array(
        'assigned_date'=>'13/11/2013',
        'start_number'=>100,
        'end_number'=>200,
        'assigned_owner'=>'test user'
        );
    Input::replace($input);
    $this->mock->shouldReceive('create')->once();
    //$this->validate(true);
    $this->call('POST', 'books', $input);

    $this->assertRedirectedToRoute('books.index');
}

我不相信我已经正确处理了虚拟用户输入。另外我不知道我应该如何隔离或测试创建票证的方法部分 - 如果要重构 - 如果是这样的话?我也找不到错误验证方法,所以暂时对此进行了评论。

我想开始测试以了解如何创建更好的代码 - 任何人都可以指出我正确的方向让我开始使用这种方法

感谢

1 个答案:

答案 0 :(得分:0)

我不熟悉laravel,但我认为你不需要Input::replace电话。您实际上已将$input传递给$this->call() ...方法。

然后在你的“外墙”上有shouldReceive方法,Laravel大量使用它。

http://laravel.com/docs/testing

所以TicketAudit::shouldReceive('batchcreate')->once();可能是一个有用的断言。 由于已经提取,因此对该方法进行单独测试是有意义的。