我有一个使用子域路由到代理商的应用程序:
foo.domain.dev -> Agency:showAction(foo)
bar.domain.dev -> Agency:showAction(bar)
domain.dev -> Agency:indexAction()
这些都对应于代理商实体和控制器。
我有一个侦听onDomainParse事件的侦听器,并将子域写入请求属性。
/**
* Listens for on domainParse event
* Writes to request attributes
*/
class SubdomainListener {
public function onDomainParse(Event $event)
{
$request = $event->getRequest();
$session = $request->getSession();
// Split the host name into tokens
$tokens = $this->tokenizeHost($request->getHost());
if (isset($tokens['subdomain'])){
$request->attributes->set('_subdomain',$tokens['subdomain']);
}
}
//...
}
然后我在控制器中使用它来重新路由到show动作:
class AgencyController extends Controller
{
/**
* Lists all Agency entities.
*
*/
public function indexAction()
{
// We reroute to show action here.
$subdomain = $this->getRequest()
->attributes
->get('_subdomain');
if ($subdomain)
return $this->showAction($subdomain);
$em = $this->getDoctrine()->getEntityManager();
$agencies = $em->getRepository('NordRvisnCoreBundle:Agency')->findAll();
return $this->render('NordRvisnCoreBundle:Agency:index.html.twig', array(
'agencies' => $agencies
));
}
// ...
}
我的问题是:
在使用WebTestCase进行测试时如何伪装?
答案 0 :(得分:7)
通过覆盖请求的HTTP标头并测试右侧页面来访问子域:
未经测试,可能包含错误
class AgencyControllerTest extends WebTestCase
{
public function testShowFoo()
{
$client = static::createClient();
$crawler = $client->request('GET', '/', array(), array(), array(
'HTTP_HOST' => 'foo.domain.dev',
'HTTP_USER_AGENT' => 'Symfony/2.0',
));
$this->assertGreaterThan(0, $crawler->filter('html:contains("Text of foo domain")')->count());
}
}
答案 1 :(得分:7)
基于基于主机的路线的Symfony文档,Testing your Controllers:
$crawler = $client->request(
'GET',
'/',
array(),
array(),
array('HTTP_HOST' => 'foo.domain.dev')
);
如果您不想使用数组参数填充所有请求,可能会更好:
$client->setServerParameter('HTTP_HOST', 'foo.domain.dev');
$crawler = $client->request('GET', '/');
...
$crawler2 = $client->request('GET', /foo'); // still sends the HTTP_HOST
如果您要更改一些参数,客户端上还有setServerParameters()
方法。