非常感謝@nicolx我可以更多地解釋發生了什麼,並提供一些進一步的指導。
正如@nicolx $request->getContentType()
所指出的那樣,您正在尋找HTTP頭部,但前綴爲HTTP_(請參閱sfWebRequest
中的第163至173行)。但是,sfBrowserBase總是爲所有頭添加HTTP_前綴。所以加在這個mod:
foreach($this->headers as $header => $value)
{
if(strotolower($header) == 'content-type' || strtolower($header) == 'content_type')
{
$_SERVER[strtoupper(str_replace('-','_',$header))] = $value;
} else {
$_SERVER['HTTP_'.strtoupper(str_replace('-','_',$header))] = $value;
}
}
這將處理ContentType
頭被設置,並在檢測到你的行動。如果您不包含HTTP_
前綴,則其他標頭將不起作用(例如,即使在測試文件中設置此項,$request->isXmlHtttpHeader()
也會失敗)。
測試方法isFormat()
未測試ContentType標頭,而是測試了Symfony路由設置sf_format。如果我將路線設置爲具有sf_format: json
例如
some_route:
url: /something/to/do
param: {module: top, action: index, sf_format: json}
那麼測試
with('request')->begin()->
isFormat('json')->
end()->
返回true。
由於我想測試標題設置,我在sfTesterRequest中添加了一個名爲isContentType()
的新測試器方法。此方法的代碼是:
public function isContentType($type)
{
$this->tester->is($this->request->getContentType(),$type, sprintf('request method is "%s"',strtoupper($type)));
return $this->getObjectToReturn();
}
調用此測試純粹變成:
with('request')->begin()->
isContentType('Application/Json')->
end()->
這實際上打破了其他頭。因爲'$ request-> getContentType()'在不使用HTTP的情況下查找標題,所以需要爲ContentType設置一個例外,但是其他的例如$ request-> isXmlHttpRequest()不需要使用HTTP_前綴。因此,foreach循環變成:'foreach($ this-> headers爲$ header => value){if(strtolower($ header)=='content-type'|| strtolower($ header)=='content_type'){ $ _SERVER [strtoupper(str_replace(' - ','_',$ header))] = $ value; }其他{$ _SERVER ['HTTP_'。strtoupper(str_replace(' - ','_',$ header))] = $ value; }' –