忽然之间的博客

Thoughts, stories and ideas.

Lumen单元测试

TestCase类

<?php

namespace Laravel\Lumen\Testing;

use Mockery;
use Exception;
use PHPUnit_Framework_TestCase;
use Illuminate\Support\Facades\Facade;
use Illuminate\Contracts\Auth\Authenticatable;

abstract class TestCase extends PHPUnit_Framework_TestCase
{
    use Concerns\MakesHttpRequests;
    # ...
}  



可以看到实现了MakesHttpRequests , 可以实现测试请求了。

自定义header

查看MakesHttpRequests.php源码,找到如何请求接口测试。


/** * Visit the given URI with a GET request. * * @param string $uri * @param array $headers * @return $this */ public function get($uri, array $headers = []) { $server = $this->transformHeadersToServerVars($headers); $this->call('GET', $uri, [], [], [], $server); return $this; } /** * Visit the given URI with a POST request. * * @param string $uri * @param array $data * @param array $headers * @return $this */ public function post($uri, array $data = [], array $headers = []) { $server = $this->transformHeadersToServerVars($headers); $this->call('POST', $uri, $data, [], [], $server); return $this; } /** * Call the given URI and return the Response. * * @param string $method * @param string $uri * @param array $parameters * @param array $cookies * @param array $files * @param array $server * @param string $content * @return \Illuminate\Http\Response */ public function call($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)

添加请求头的测试代码

<?php

use Illuminate\Http\Response;

class RequestTest extends TestCase {

    public $response;

    function __construct()
    {
        $this->response = new Response();
    }

    public function testHeader()
    {

       $this->call('POST', '/test',[],[],[], ['HTTP_Authorization' => 'content'],[]);

        $foo = $this->response->getContent();

        $this->assertEquals('yes',$foo);
    }

}

Route::post('/test', function()
{
    return \Request::header('Authorization') ? 'yes' : 'no';

});

还可以这样, 在getpost方法中定义第三个参数。


<?php $this->post('blogs', ['title' => 'awesome blog post'], ['HTTP_Authorization' => 'Bearer' . $token]);