Can Behat be integrated with PHPUnit?

244 Views Asked by At

I have been setting up Behat in order to facilitate BDD as a testing framework for my company. The ask is to also incorporate it with PHPUnit, so as to derive the benefits of that platform, with the readability of the Gherkin syntax of the Behat scenarios.

My first attempt at integration with PHPUnit was to make php exec() calls out to the command line from the Behat Feature file, and base the results of each scenario step on the feedback from that PHPUnit test. This, however, feels cumbersome, and that there should be a way to more tightly integrate these tools, hopefully allowing Behat to call PHPUnit tests directly.

/**
 * @When <invoice_custcode>
 */
public function invoiceCustcode()
{
    $returnValue = "";
    $output = "";
    exec("phpunit BDDTest",$output,$returnValue);
    echo "returned with status ".$returnValue." and output=".print_r($output);

}

This far, the closest I have come is this project by Jonathan Shaw from 2019, but it doesn't seem to speak completely to my question.

https://medium.com/@jonathanjfshaw/write-better-tests-by-using-behat-with-phpunit-ddb08d449b73

1

There are 1 best solutions below

1
Barry On

The way to "integrate" phpunit would be to use it... the behat composer.json already includes php-unit... and if you want to use mockery, just include that... and write your context to support your domain language features:

/**
 * @When I invoice code :invoice_code
 */
public function invoiceCustcode($invoice_code)
{
    //make mock
    $fakeDataRetriever = m::mock('My\Data\Api\Retriever');
    $fakeDataRetriever->shouldReceive('getData')->andReturn(['fake_name' => 'fake_value']);

    //test something with this mock
    $return = (new Something($fakeDataRetriever))->someFunction();

    //do an assert
    $this->assertSame($return, 'expected return value');
}

Then there are different hooks to do setup and teardown functions, except they are called beforeScenario and afterScenario hooks... and there are many more of them for more control.

Please read the docs as behat offers a lot... for example transformations making converting text variables in feature files to object automatically.