How to use the PHPUnit Test in Laravel 5.1

Source: Internet
Author: User

Access all tutorials in sprocket icon.

June, from author Bill Keck.

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

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

vendor/bin/phpunit --version

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

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

PHPUnit 4.7.2 by Sebastian Bergmann and contributors.

Use the path, which works for the rest of the tutorial.

Ok, great, so what do we run an actual test? Well, let's start by looking at the example test this comes with the Laravel install. Under your project folder, you'll see a tests folder. Inside you'll see exampletest.php:

<?phpuse 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'll run all tests in the folder. If has a fresh install of Laravel, the test should find "Laravel 5 ' on the Welcome view, which is where the '/' route poi NTS to. You'll get a response. The first line tells what many milliseconds it took to run the test and how much memory it consumed.

The second line would be a highlighted in green, and look for something like this:

OK(1 test, 1 assertion)

Now let's make it fail, so we can see what the 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 and include here, so I'll give you the relevant bits. It starts with:

Time: 719 ms, Memory: 15.50MbThere was 1 failure:1) ExampleTest::testBasicExampleFailed asserting that ‘

Then it prints the HTML from the page. Then your 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 was 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-to-miss the fact that it didn ' t pass. Now you would think this every time you run a test and you would get red or green, but there ' s actually a third option.

If you had a mistake in the test code itself, the test doesn ' t run at all and it would simply return a command prompt on a New line. You can test the 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 have made this incredibly easy. Let's create a test for registration. This assumes your registration setup for your app. If you don ' t, set the up first, then come the 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:

<?phpuse 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! Does I even need to explain what it does? Obviously the first parameter in each chained method are the value and the second is the name of the field.

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

Note that if your paths to registration are different than mine, you'll have the to adjust your test accordingly. Also, if you have different input fields in your form, adjust accordingly.

You'll also note that we're using a trait in our test class named Databasetransactions. What's this does are rollback the insert to the database, so you don't have to gum it up with test data. Using the databasemigrations trait would rollback the migration, which'll 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 is extending TestCase for our test classes, not phpunit_framework_testcase.

Ok, so the ' s going to wrap up we primer on PHPUnit testing in Laravel 5.1.

I hope you has 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 as if you can, thanks!

I don ' t has a donate button, but If you would like-to-support my work and learn more on Laravel, you can do so by Buyi ng One of my books, Laraboot:laravel 5* for beginners, I really appreciate it.

How to use the PHPUnit Test in Laravel 5.1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.