问题
I've read the documentation from Symfony2 but it doesn't seem to work. Here's my functional test:
public function testSearch()
{
$client = static::createClient();
$crawler = $client->request('POST', '/search/results', array('term' => 'Carteron'));
$this->assertTrue($crawler->filter('html:contains("Carteron")')->count() > 0);
$this->assertTrue($crawler->filter('html:contains("Auctions")')->count() > 0);
}
In my controller the "term" parameter is null when this request comes in. However, search works just fine when I perform it on the site, so I know its a problem with setting up the test.
回答1:
I had the same problem, neither $request->query
nor $request->request
worked. Both did the same for me: it returned $default
, not the given $parameters
(Symfony 2.3).
Same behaviour as chris, in normal web browsers it works. I fixed this by replacing:
public function searchResultsAction($name)
{
$request = Request::createFromGlobals();
$term = trim($request->request->get('term'));
return $this->searchResultsWithTermAction($term);
}
With:
public function searchResultsAction(Request $request, $name)
{
// do NOT overwrite $request, we got it as parameter
//$request = Request::createFromGlobals();
$term = trim($request->request->get('term'));
return $this->searchResultsWithTermAction($term);
}
So createFromGlobals()
does only work if $_GET
and $_POST
are set. Shich is not the case if you use the symfony test client. you have to add the $request
parameter to the action.
(I used $name
as a GET parameter in my routing)
回答2:
I've never gotten an answer to this, but have implemented a work around that seems to work for my testing purposes. I'd love to hear feedback or get a real answers to this questions.
What I've done is create a 2nd route for the purposes of testing.
In real usage the uri would be /search/results?term=searchtermhere
For the purposes of testing, this didn't work. I could never get access to the term value when invoked via the automated test.
So what I've done is create a 2nd route just for testing which has a uri of /search/results/{searchtermhere}
.
Then my action class used for a real search would call down to another function and pass the term to the function:
public function searchResultsAction()
{
$request = Request::createFromGlobals();
$term = trim($request->request->get('term'));
return $this->searchResultsWithTermAction($term);
}
So my functional tests would excersize searchResultsWithTermAction()
, so the only code coverage I'm missing from this workaround is the extraction of the term from the request.
回答3:
I don't know if anyone is still searching for an answer to this, but basically the problem is that you are looking in the wrong place for the parameter.
For your example you would need:
$term = trim($request->query->get('term'));
Hope this helps!
来源:https://stackoverflow.com/questions/8439782/how-do-i-create-a-functional-test-which-includes-a-post-to-a-page-with-parameter