,并添加案例代码。
Behat 中外部文件中的步骤定义Behat 是一个使用 PHP 编写的行为驱动开发(BDD)框架,可以帮助开发人员和非技术人员之间更好地交流和理解需求。Behat 提供了一种将自然语言需求转化为可执行的测试的方法。除了内置的步骤定义外,Behat 还允许我们将步骤定义存储在外部文件中,以便更好地组织和维护测试代码。使用外部文件定义步骤在 Behat 中,我们可以使用外部文件来定义测试中使用的步骤。这样做的好处是可以将步骤定义从测试代码中分离出来,提高代码的可读性和可维护性。下面是一个例子:features/bootstrap/FeatureContext.phpphpuse Behat\Behat\Context\Context;use Behat\Gherkin\Node\PyStringNode;use Behat\Gherkin\Node\TableNode;class FeatureContext implements Context{ /** * @Given the following users: */ public function theFollowingUsers(TableNode $table) { // 在这里编写你的代码来处理给定的用户列表 } /** * @When /^I log in as "([^"]*)" with password "([^"]*)"$/ */ public function iLogInAsWithPassword($username, $password) { // 在这里编写你的代码来执行登录操作 } /** * @Then /^I should see the welcome message "([^"]*)"$/ */ public function iShouldSeeTheWelcomeMessage($message) { // 在这里编写你的代码来验证欢迎消息是否正确显示 }}在上面的例子中,我们定义了三个步骤,分别用于创建用户、登录和验证欢迎消息。这些步骤的实现代码可以根据具体需求进行编写。将步骤定义存储在外部文件中为了将步骤定义存储在外部文件中,我们需要创建一个新的 PHP 类,并实现 Context 接口。然后,我们可以将步骤定义移动到新的类中,并在 FeatureContext 类中使用该类。下面是一个示例:features/bootstrap/ExternalStepsContext.php
phpuse Behat\Behat\Context\Context;use Behat\Gherkin\Node\PyStringNode;use Behat\Gherkin\Node\TableNode;class ExternalStepsContext implements Context{ /** * @Given the following users: */ public function theFollowingUsers(TableNode $table) { // 在这里编写你的代码来处理给定的用户列表 } /** * @When /^I log in as "([^"]*)" with password "([^"]*)"$/ */ public function iLogInAsWithPassword($username, $password) { // 在这里编写你的代码来执行登录操作 } /** * @Then /^I should see the welcome message "([^"]*)"$/ */ public function iShouldSeeTheWelcomeMessage($message) { // 在这里编写你的代码来验证欢迎消息是否正确显示 }}使用外部步骤定义要在 FeatureContext 类中使用外部步骤定义,我们需要添加一个 use 语句和一个方法来实例化 ExternalStepsContext 类,并将其作为一个子上下文。下面是一个示例:features/bootstrap/FeatureContext.php
phpuse Behat\Behat\Context\Context;use Behat\Gherkin\Node\PyStringNode;use Behat\Gherkin\Node\TableNode;use ExternalStepsContext;class FeatureContext implements Context{ private $externalStepsContext; public function __construct() { $this->externalStepsContext = new ExternalStepsContext(); } /** * @Given the following users: */ public function theFollowingUsers(TableNode $table) { return $this->externalStepsContext->theFollowingUsers($table); } /** * @When /^I log in as "([^"]*)" with password "([^"]*)"$/ */ public function iLogInAsWithPassword($username, $password) { return $this->externalStepsContext->iLogInAsWithPassword($username, $password); } /** * @Then /^I should see the welcome message "([^"]*)"$/ */ public function iShouldSeeTheWelcomeMessage($message) { return $this->externalStepsContext->iShouldSeeTheWelcomeMessage($message); }}通过使用外部文件中的步骤定义,我们可以更好地组织和维护 Behat 测试代码。这种方法使测试更具可读性,并且可以提高开发人员和非技术人员之间的交流。在实际项目中,我们可以根据具体需求将步骤定义分散到不同的文件中,以便更好地组织和管理测试代码。以上是关于 Behat 中外部文件中的步骤定义的说明和示例代码。希望这篇文章对你理解和使用 Behat 框架有所帮助。