PHP code example of matthiasnoback / behat-expect-exception
1. Go to this page and download the library: Download matthiasnoback/behat-expect-exception library. Choose the download type require. 2. Extract the ZIP file and open the index.php. 3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
matthiasnoback / behat-expect-exception example snippets
use Behat\Behat\Context\Context;
use BehatExpectException\ExpectException;
final class FeatureContext implements Context
{
// Use this trait in your feature context:
use ExpectException;
/**
* @When I try to make a reservation for :numberOfSeats seats
*/
public function iTryToMakeAReservation(int $numberOfSeats): void
{
/*
* Catch an exception using $this->shouldFail().
* If the code in the callable doesn't throw an exception, shouldFail()
* itself will throw an ExpectedAnException exception.
*/
$this->shouldFail(
function () use ($numberOfSeats) {
// This will throw a CouldNotMakeReservation exception:
$this->reservationService()->makeReservation($numberOfSeats);
}
);
}
/**
* @Then I should see an error message saying: :message
*/
public function confirmCaughtExceptionMatchesExpectedTypeAndMessage(string $message): void
{
$this->assertCaughtExceptionMatches(
CouldNotMakeReservation::class,
$message
);
}
/**
* @When I make a reservation for :numberOfSeats seats
*/
public function iMakeAReservation(int $numberOfSeats): void
{
/*
* Catch a possible exception using $this->mayFail().
* If the code in the callable doesn't throw an exception,
* then it's not a problem. mayFail() doesn't throw an
* ExpectedAnException exception itself in that case.
* You can still use assertCaughtExceptionMatches(), but
* it will throw an ExpectedAnException if no exception was
* caught.
*/
$this->mayFail(
function () use ($numberOfSeats) {
// This might throw a CouldNotMakeReservation exception:
$this->reservationService()->makeReservation($numberOfSeats);
}
);
}
}