无论如何在phpunit测试用例中使用Behat?

问题描述 投票:0回答:2

我一直在使用类似Behat英语的测试语言(Gherkin?)编写测试脚本,但很快就出现了它的显着局限性。

如果我可以在我设置的phpunit测试脚本中用PHP执行这些测试,那么我可以大大扩展我可以添加的测试。 (我正在使用FuelPHP)。

我一直在修补几个小时试图让Behat在PHPUNIT测试脚本中执行,但运气不好。

这可能吗?

php phpunit behat fuelphp mink
2个回答
2
投票

我觉得你很困惑,因为你所说的并没有多大意义。如果您很难用代码表达逻辑,那么您应该就此提出具体问题。

Behat和Mink都是用PHP编写的,你用PHP编写你的上下文,有一些插件可以让生活更轻松(也用php编写)。事实上,当你运行它们时,所有的测试都是在PHP中执行的......是的!

如果你想比较两个页面的数据,你可以简单地创建一个这样的步骤:

/**
 * @Then /^the page "(.+)" and the page "(.+)" content should somehow compare$/
 */
public function assertPageContentCompares($page1, $page2)
{
    $session = $this->getSession();
    $session->visit($page1);
    $page1contents = $session->getPage()->getHtml();

    $session->visit($page2);
    $page2contents = $session->getPage()->getHtml();

    // Compare stuff…
}

除了显而易见的,您可以使用PHPUnit与Behat / Mink一起制作断言,即在步骤定义中。大多数(并非所有)PHPUnit断言都是静态方法,使用它们就像这样简单:

PHPUnit_Framework_TestCase::assertSame("", "");

您可以将Selenium(可能还​​有其他框架)与PHPUnit一起使用,如果这更多是关于单元测试而不是功能测试,the official documentation tells how

如果你只是讨厌Gherkin,那么你对Behat的关注并不多 - 它就是它的核心。有了PhpStorm 8,它有很好的支持,您可以轻松浏览代码并快速重构。如果这没有削减它,那么还有另一个很好的替代Behat叫做Codeception,你可以使用纯PHP来定义你的测试。也许这就是你要找的东西。


0
投票

是。您可以使用我创建的库:jonathanjfshaw/phpunitbehat

你的phpunit测试将如下所示:

    namespace MyProject\Tests;

    use PHPUnit\Framework\TestCase;
    use PHPUnitBehat\TestTraits\BehatTestTrait;

    class MyTestBase extends TestCase {
      use BehatTestTrait;
    }
    namespace MyProject\Tests;

    class MyTest extends MyTestBase {

      protected $feature = <<<'FEATURE'
    Feature: Demo feature
      In order to demonstrate testing a feature in phpUnit
      We define a simple feature in the class
    Scenario: Success
        Given a step that succeeds
    Scenario: Failure
        When a step fails

      Scenario: Undefined
        Then there is a step that is undefined
    FEATURE;

      /**
       * @Given a step that succeeds
       */
      public function aStepThatSucceeds() {
        $this->assertTrue(true);
      }

      /**
       * @When a step fails
       */
      public function aStepFails() {
        $this->assertTrue(false);
      }
    }

我写了a blog post explaining why I think this is not a bad idea

© www.soinside.com 2019 - 2024. All rights reserved.