php – 如何在Laravel中基于application / json标头加载路由
发布时间:2020-05-31 00:55:30 所属栏目:PHP 来源:互联网
导读:我正在使用application / json标头控制我的控制器在收到请求时的行为方式.我需要在单元测试中使用POST来包含一个application / json头. 我试过了: public function testStore() { $this-validator -shouldReceive(validate)
|
我正在使用application / json标头控制我的控制器在收到请求时的行为方式.我需要在单元测试中使用POST来包含一个application / json头. 我试过了: public function testStore()
{
$this->validator
->shouldReceive('validate')
->once()
->with($this->attributes)
->andReturn(true);
$this->repository
->shouldReceive('create')
->once()
->with($this->attributes)
->andReturn($this->entity);
$this->controller
->shouldReceive('creationSucceeded')
->once()
->with($this->entity);
$this->client->request('POST','shared/users',[],[
'HTTP_CONTENT_TYPE' => 'application/json'
],json_encode($this->attributes));
$this->assertResponseStatus(201);
}
而且我的控制器中的Request :: isJson()继续返回false. 我也尝试过使用’CONTENT_TYPE’=> ‘application / json’而不是上面的HTTP_CONTENT_TYPE. 就我而言,我使用Content-Type来确定要加载哪些控制器.这对我不起作用,因为当运行TestCase-> createApplication()时路由被加载到内存中.这意味着我的标题没有效果.我最终制作了一个RouteInflector,允许我强制我的测试使用Api路线. class ApiTestCase extends TestCase
{
/**
* @inheritDoc
*/
public static function setUpBeforeClass()
{
/**
* Routes are loaded into memory before tests are run.
* Because of this,we can't have routing logic based on
* heads. Using the RouteInflector we can override
* header to createApplication() and must use a constant
* to force the RouteInflector to use Api controllers.
*/
RouteInflector::isJson(true);
}
public function setUp()
{
parent::setUp();
//Lets do this right
$this->client->setServerParameter('HTTP_CONTENT_TYPE','application/json');
$this->client->setServerParameter('HTTP_ACCEPT','application/json');
}
}
偏转: class RouteInflector
{
/** @var bool */
protected static $isJson = false;
/**
* Review the request details and determine which controller
* subpackage should be used.
* We could also check the request source to help determine the
* package.
*
* Defaults to Web.
*
* @return string
*/
public function getControllerSubpackage()
{
if (self::isJson() || Request::isJson()) {
return 'Api';
}
return 'Web';
}
/**
* Used by tests to tell routing that the current request
* is a json request.
*
* @see TestsApiTestCase
*
* @param bool|null $isJson
*
* @return bool Only provided if parameter is null
*/
public static function isJson($isJson = null)
{
if (is_null($isJson)) {
return self::$isJson;
} else {
self::$isJson = $isJson;
}
}
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
