Mohamed Benhida

admin@devma.net

December 29, 2017

PHPUnit Test in Laravel

Phpunit testing is something that every php developer must know.

Instead of testing manually in the browser we want to make a testing code so we can launch it every time we need and launch it with all the other test so we can if there is another test that will help our test to fail and we can know this for sure on manual testing by refreshing the page every time and sending the request etc ...

Let's check now the default test that came with our laravel project in

tests/Feature/ExampleTest.php

  public function testBasicTest()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }

this test make a get request to your index page and if it works we will see a 200 Status then the test will pass.

to launch the test you need to go in your directory on consol then tape 

vendor/bin/phpunit 

for Mac users you can make an alias with this command alias phpunit="vendor/bin/phpunit"

you will see a result like this the green bar mean that your test passed.

phpunit

If you want the function count in test you need to add the word test in the beginning of the function name or add on top of the function the /** @test */ comment 

public function testSomething()
{

}
//Or

/** @test */
public function Something()
{

}

Now we want to test if we can fetch the post by passing the slug instead of id you can learn more about this here

we create our test class with this command

php artisan make:test Post

/** @test */
    public function it_can_fetch_a_post_by_passing_slug()
    {
        //Creating the post
        $post = factory(\App\Post::class)->create();

        //Test if we can see the title post on the browser
        $this->get($post->path())
            ->assertStatus(200)
            ->assertSee($post->title);
    }

we create the post by making the factory on

database/factories/UserFactory.php

$factory->define(App\Category::class, function(Faker $faker) {
    return [
        'name' => $faker->name,
        'slug' => $faker->slug
    ];
});

$factory->define(App\Post::class, function (Faker $faker)
{
    return [
        'title'       => $faker->sentence,
        'slug'        => $faker->slug,
        'content'     => $faker->randomHtml(),
        'description' => $faker->sentence,
        'image'       => $faker->name,
        'category'    => function ()
        {
            return factory(\App\Category::class)->create()->id;
        }
    ];
});

Now if we follow the stuff that we did on our TIP the test will give us green bar

if we want to test our function it_can_fetch_a_post_by_passing_slug we add --filter function Name to our command

vendor/bin/phpunit --filter it_can_fetch_a_post_by_passing_slug

phpunit

I Hope that could help you !

© Mohamed Benhida.

Blog | Packages | About