Bazen behat senaryolarının sonuçları sabit olmayabilir, bu nedenle testler bozulabilir. Bu tarz problemleri önlemek için PHP Matcher kullanılır.


Composer.json


Composer ile "coduo/php-matcher": "1.1.6" paketinin yüklenmiş olması gereklidir.


Controller


/**
* @Route("user")
*/
class UserController extends Controller
{
/**
* @param Request $request
*
* @Route("")
* @Method({"GET"})
*
* @return Response
*/
public function listAction(Request $request)
{
$countries = [
'GB' => 'Great Britain',
'DE' => 'Germany',
'TR' => 'Turkey'
];

return $this->createJsonResponse(array_rand($countries));
}
}

Feature example


Gösterilen @string@ haricindeki diğer seçenekler için yukarıdaki linki ziyaret ediniz.


Feature: Handling dynamic results

Scenario: I can handle dynamic response content
Given I am on "/user"
Then the response status code should be 200
And the response should contain dynamic json:
"""
@string@
"""

FeatureContext.php


Basit bir içerik, json kod vs. gibi çoğu bilgiyi kontrol edebilirsiniz. En son responseyi görmek için $this->getBrowser()->getLastResponse()->getContent() kodunuda kullanabilirsiniz.


namespace Application\BackendBundle\Features\Context;

use Behat\Gherkin\Node\PyStringNode;
use Behat\MinkExtension\Context\MinkContext;
use Coduo\PHPMatcher\Factory\SimpleFactory;

class FeatureContext extends MinkContext
{
/**
* Checks that response body contains JSON from PyString.
*
* @param PyStringNode $jsonString
*
* @Then /^(?:the )?response should contain dynamic json:$/
*/
public function theResponseShouldContainDynamicJson(PyStringNode $jsonString)
{
$expectedJson = $jsonString->getRaw();
$responseJson = $this->getSession()->getPage()->getContent();

if (null === $expectedJson) {
throw new \RuntimeException("Can not convert given JSON string to valid JSON format.");
}

$factory = new SimpleFactory();
$matcher = $factory->createMatcher();
$match = $matcher->match($responseJson, $expectedJson);

if ($match !== true) {
throw new \RuntimeException("Expected JSON doesn't match response JSON.");
}
}
}

Sonuç


Inanzzz-MBP:football inanzzz$ bin/behat
Feature: Handling dynamic results

Scenario: I can handle dynamic response content
Given I am on "/user"
Then the response status code should be 200
And the response should contain dynamic json:
"""
@string@
"""

1 scenario (1 passed)
3 steps (3 passed)
0m5.87s