How Use PHPUnit Test in Laravel 5.1

Access all tutorials in sprocket icon.

June 12, 2015 from author Bill Keck.

Sometimes for beginners, the idea of PHPUnit testing code can be scary. You find yourself having to install the test framework, learn a whole new series of commands and methods, and half the time, you have no idea why it doesn’t work.

Fortunately, with Laravel 5.1, testing is incredibly easy, it is already integrated into the framework, ready to go, out of the box. To confirm this, you can run a simple command from the command line:



vendor/bin/phpunit --version

Tip for anyone who gets an error message about composer dependencies from the above. Try running:



vendor/phpunit/phpunit/phpunit --version 

In any event, once you have the correct path, it will return the following, and you know you are good to go:



PHPUnit 4.7.2 by Sebastian Bergmann and contributors.

Use the path that works for the rest of the tutorial.

Ok, great, so how do we run an actual test? Well, let‘s start by looking at the example test that comes with the Laravel install. Under your project folder, you will see a tests folder. Inside you will see ExampleTest.php:



<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->visit(‘/‘)
             ->see(‘Laravel 5‘);
    }
}

To run this test, just call it from the command line like so:



vendor/bin/phpunit

That will run all tests in the folder. If have a fresh install of Laravel, the test should find "Laravel 5‘ on the welcome view, which is where the ‘/‘ route points to. You will get a two line response. The first line tells you how many milliseconds it took to run the test and how much memory it consumed.

The second line will be highlighted in green, and look something like this:



OK(1 test, 1 assertion)

Now let‘s make it fail, so we can see what happens when it fails. Change ‘Laravel 5‘ to ‘Laravel 6‘ inside the test and run it again with:



vendor/bin/phpunit

You can see it gives a lot more output. There‘s too much for me to include here, so I‘ll give you the relevant bits. It starts with:



Time: 719 ms, Memory: 15.50Mb

There was 1 failure:

1) ExampleTest::testBasicExample
Failed asserting that ‘

Then it prints the html from the page. Then you get the following line:



‘ matches PCRE pattern "/Laravel 6/i".

That‘s the end of the statement of the failed assertion. So it‘s telling you precisely how it failed. How cool is that?

And then of course you get the red highlighted summary block:



FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

With the red highlighting, there‘s no way to miss the fact that it didn‘t pass. Now you would think that every time you run a test, you would get red or green, but there‘s actually a third option.

If you have a mistake in the test code itself, the test doesn‘t run at all and it will simply return a command prompt on a new line. You can test this by removing the semicolon from inside the test method and running the test again.

One of the more time consuming tasks that I hear programmers talk about is testing forms. Laravel has made this incredibly easy. Let‘s create a test for registration. This assumes you have registration setup for your app. If you don‘t, set that up first, then come back to this tutorial.

So let‘s use artisan to make our test stub:



php artisan make:test RegistrationTest

Now, inside the tests folder, let‘s modify RegistrationTest.php with the following:



<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class RegistrationTest extends TestCase
{

    use DatabaseTransactions;

    public function testNewUserRegistration()
    {
        $this->visit(‘auth/register‘)
            ->type(‘bob‘, ‘name‘)
            ->type(‘[email protected]‘, ‘email‘)
            ->type(‘hello1‘, ‘password‘)
            ->type(‘hello1‘, ‘password_confirmation‘)
            ->press(‘Register‘)
            ->seePageIs(‘/‘);
    }

}

Look at how intuitive the syntax is! Do I even need to explain what it does? Obviously the first parameter in each chained method is the value and the second is the name of the field.

For a full list of methods, check testing docs, they are well written and clear.

Note that if your path to registration is different than mine, you will have to adjust your test accordingly. Also, if you have different input fields in your form, adjust accordingly.

You‘ll also note that we are using a trait in our test class named DatabaseTransactions. What this does is rollback the insert to the database, so you don‘t have to gum it up with test data. Using the DatabaseMigrations trait will rollback the migration, which will drop the table. The WithoutMiddleware trait allows it to skip middleware for testing purposes.

You can read up on PHPUnit on the Official PHPUnit Site. Just remember that inside Laravel, we are extending TestCase for our test classes, not PHPUnit_Framework_TestCase.

Ok, so that‘s going to wrap up our primer on PHPUnit testing in Laravel 5.1.

I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials. Please comment, share, and like if you can, thanks!

I don’t have a donate button, but If you would like to support my work and learn more about Laravel, you can do so by buying one of my books, Laraboot: laravel 5* For Beginners, I really appreciate it.

时间: 2024-12-13 10:28:34

How Use PHPUnit Test in Laravel 5.1的相关文章

Laravel 项目运行 phpunit 测试结果只显示点号

在laravel 项目的根目录下,运行 phpunit 只显示 点号的情况 我尝试将 tests/Unit 和 tests/Feature 目录将 ExampleTest.php 文件删除,然后再运行phpunit,就不只显示点号了 其中尝试了另外安装phpunit,降低 Laravel 安装的版本,重新安装一个vagrant LNMP环境,同一个项目运行 phpunit 都是只显示点号 看到 Homestead中运行 phpunit是运行 vendor/bin/phpunit的文件 在 Hom

Laravel 5.1 Beauty - Testing

Note this is the fourth step of the tutorial. In this chapter we'll create a project to use throughout the rest of the book and explore various options for testing. Along the way a service class to convert Markdown formatted text files to HTML will b

基于 Laravel 开发博客应用系列 —— 从测试开始(二):使用Gulp实现自动化测试

3.使用 Gulp 进行 TDD(测试驱动开发) Gulp 是一个使用 JavaScript 编写的自动化构建工具.用于对前端通用任务(如最小化.压缩.编译)进行自动构建.Gulp 还可以用来监控源代码的改动并自动运行任务. Laravel 5.1 提供了一个封装 Gulp 的 Laravel Elixir 包,可用于轻松构建 Gulp 任务,Elixir 为 Gulp 添加了优雅的语法,Elixir 之于 Gulp 正如 Laravel 之于 PHP. Gulp 最常见的用法之一就是自动构建单

基于 Laravel 开发博客应用系列 —— 从测试开始(一):创建项目和PHPUnit

1.创建博客项目 我们将遵循上一节提到的六步创建一个新 Laravel 5.1 项目的步骤,创建本节要用到的博客项目 —— blog. 首先,在本地主机安装应用骨架: [email protected]:~/Code$ composer create-project laravel/laravel blog --prefer-dist 接下来,编辑 Homestead.yaml,添加站点信息及数据库信息: sites: - map: test.app to: /home/vagrant/Code

Laravel系列教程一:安装及环境配置

免费视频教程地址https://laravist.com/series/laravel-5-basic 最近在SF上面看到越来越多的Laravel相关的问题,而作为一个Laravel的脑残粉,本来打算有机会录视频教程放出来的,不过这个计划貌似由于某些原因必须得推迟一段时间,所以现在先把文章的系列教程写出来吧. 首先需要说明的是,这个教程对于完全没有上手Laravel的人来说,我尽量将一些概念和重点说清楚,不过你也不需要担心这需要花很多时间来跟着这个教程学习Laravel,我相信,如果你认认真真跟

Linux laravel安装

第一步:安装php套件 目前为止laravel是5.1版本,需要对php有要求,要php5.59以上 The Laravel framework has a few system requirements. Of course, all of these requirements are satisfied by the Laravel Homestead virtual machine: * PHP >= 5.5.9 * OpenSSL PHP Extension * PDO PHP Exte

Laravel 5.2 INSTALL- node&#39;s npm and ruby&#39;s bundler.

https://getcomposer.org/doc/00-intro.md Introduction# Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. Dependency management# Compose

《learning laravel》翻译第三章-----搭建我们第一个网站

重要: 这是一个稳定的版本. 让我们知道你的喜好. 我们将会修改bug和错误,并且定期更新所有章节. 第二章: 搭建我们第一个网站 既然我们知道如何安装Laravel了, 那现在就开始通过我们自己的方式来搭建我们第一个基于Laravel的网站吧. 在本章中,通过搭建Laravel应用程序你将会很方便得学习Laravel的结构,路由,控制器,模板,Artisan命令,Elixir API和很多基础特性. 剖析Laravel结构 假设你将Laravel安装在 ~/Code/Laravel目录.跳转到

为什么Laravel是最成功的PHP框架?

Laravel 是一个有着美好前景的年轻框架,它的社区充满着活力,相关的文档和教程完整而清晰,并为快速.安全地开发现代应用程序提供了必要的功能.在近几年对PHP 框架流行度的统计中,Laravel始终遥遥领先.那么是什么让Laravel成为最成功的PHP框架? 2011 年,Taylor Otwell将Laravel作为一种包含全新现代方法的框架介绍给大家.Laravel最初的设计是为了面向MVC架构的,它可以满足如事件处理.用户 身份验证等各种需求.另外它还有一个由管理数据库强力支持,用于管理