How to create a functional test that includes POST on a page with parameters?

I read the documentation from Symfony2, but it doesn't seem to work. Here is 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 arrives. However, the search is performed very well when I execute it on the site, so I know its problem with the test setup.

0
source share
3 answers

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).

Such behavior as chris works in regular web browsers. I fixed this by replacing:

 public function searchResultsAction($name) { $request = Request::createFromGlobals(); $term = trim($request->request->get('term')); return $this->searchResultsWithTermAction($term); } 

FROM

 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() only works when setting $_GET and $_POST . Shih is not the case if you are using the symfony test client. you need to add the $request parameter to the action.

(I used $name as the GET parameter in my routing)

+1
source

I have never received an answer to this question, but have implemented work that seems to work for my testing purposes. I would like to hear feedback or get answers to these questions.

What I did was create a 2nd route for testing.

In actual use, uri will be /search/results?term=searchtermhere

For testing purposes, this did not work. I have never been able to access the meaning of a term when called using an automatic test. So, I created the 2nd route for testing only, which has uri /search/results/{searchtermhere} .

Then my action class, used for a real search, will call another function and pass this term to the function:

 public function searchResultsAction() { $request = Request::createFromGlobals(); $term = trim($request->request->get('term')); return $this->searchResultsWithTermAction($term); } 

So, my functional tests will be excersize searchResultsWithTermAction() , so the only code coverage that I am missing in this workaround is extracting the term from the query.

0
source

I don’t know, someone is still looking for the answer to this question, but basically the problem is that you are looking for the wrong place for the parameter.

For your example, you will need:

 $term = trim($request->query->get('term')); 

Hope this helps!

0
source

Source: https://habr.com/ru/post/906875/


All Articles