Thursday 19 March 2020

Laravel Unit Tests For PHP

// Create a test in the Unit directory...
php artisan make:test UserTest --unit

This will create a UserTest.php in Unit/Test

// Run
./vendor/bin/phpunit

// Show debug mesage
./vendor/bin/phpunit --debug

// Output message
use print_r() then run with --debug flag

// Store value for later use in the class, create static attributes
   /**
     * Static class attributes
     * @string
     */   
    public static $static

// Set by using self::static

// Each test class is created and destoryed, can not make two tests depend on each other

// Check if array contains something in test
$this->assertContains( $randad, $adUnitArr );
// Create get request

    /**
     *  Test /company end point
     *
     * @return void
     */
    public function testGet() {
        $response = $this->withHeaders([
            'Accept' => 'application/json',
            'Content-Type' => 'application/json;charset=utf-8',

        ]) ->json('GET',  '/api/company', 
                [
                    'page' => 1,
                    'limit' => 10,
                ]
        );

        // Response should be json string
        $return_array = json_decode($response->getContent(), TRUE);
        $response->assertStatus(200);        
        // print_r($return_array);
        $this->assertArrayHasKey('items', $return_array);
    }
// Create post request
<?php

class ExampleTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $response = $this->withHeaders([
            'X-Header' => 'Value',
        ])->json('POST', '/user', ['name' => 'Sally']);

        $response
            ->assertStatus(201)
            ->assertJson([
                'created' => true,
            ]);
    }
}
https://stackoverflow.com/questions/31638220/test-if-array-contains-value-using-phpunit
https://stackoverflow.com/questions/10228/run-phpunit-tests-in-certain-order
https://stackoverflow.com/questions/151969/when-to-use-self-over-this
https://stackoverflow.com/questions/8835607/dependent-tests-between-two-testcase-classes-in-phpunit
https://laravel.com/docs/5.8/http-tests
https://laravel.com/docs/5.8/testing#creating-and-running-tests

No comments:

Post a Comment