Codeception在CEST内的所有测试之前运行

时间:2016-04-27 10:07:00

标签: php codeception

我希望在特定Cest中的所有测试之前运行一些东西,然后在所有测试运行后清理它,类似于PHPUnit中的setUpBeforeClass和tearDownAfterClass方法。

是否有方法在Codeception中执行此类操作?

4 个答案:

答案 0 :(得分:3)

在Codeception专家为您提供可靠的方法之前,我目前对此问题有一个粗略的解决方案。

只需在您现有的所有actor(测试用例)之上创建另一个Actor,就像这样:

class MyCest
{

function _before(AcceptanceTester $I)
{
    $I->amOnPage('/mypage.php');
}

public function _after(AcceptanceTester $I)
{

}

function beforeAllTests(AcceptanceTester $I,\Page\MyPage $myPage,\Helper\myHelper $helper){
    //Do what you have to do here - runs only once before all below tests
    //Do something with above arguments
}

public function myFirstTest(AcceptanceTester $I){
    $I->see('Hello World');
}

function afterAllTests(){
    //For something after all tests
}
}

您可以将函数AllAllTests公开,但不受保护,也不应该以“ _”开头,以便在所有测试之前运行。

另一组函数将在所有测试开始之前仅运行一次,应在/tests/_support/Helper/Acceptance.php中实例化以进行接受等等。在此您可以调用函数:

// HOOK: used after configuration is loaded
public function _initialize()
{
}

// HOOK: before each suite
public function _beforeSuite($settings = array())
{
}

有关更多功能,请访问:https://codeception.com/docs/06-ModulesAndHelpers#Hooks

答案 1 :(得分:2)

从Codeception的角度来看,Cest类只是一堆Cept场景。 没有对象范围,也没有类挂钩之前/之后。

我的建议是改用Test格式并使用PhpUnit钩子。

测试格式扩展了PHPUnit_Framework_TestCase,因此setUpBeforeClass应该可以工作。

答案 2 :(得分:1)

您可以在functional.suite.yml中添加新帮助:

class_name: FunctionalTester
modules:
    enabled:
      - tests\components\helpers\MyHelper

在帮助程序中,您可以使用_before_after方法:

class FixtureHelper extends \Codeception\Module
{
    /**
     * Method is called before test file run
     */
    public function _before(\Codeception\TestCase $test)
    {
        // TODO: Change the autogenerated stub
    }

    /**
     * Method is called after test file run
     */
    public function _after(TestCase $test)
    {
        // TODO: Change the autogenerated stub
    }
}

TestCase方法可以帮助您确定执行_before_after的必要性。

答案 3 :(得分:0)

根据您所说的“运行某物”和“清理它”的含义,您可以使用 PHP 标准的构造函数和析构函数。

这个解决方案对我来说似乎更清楚,但请记住,您无法访问 AcceptanceTester $IScenario $scenario 来自那里,因此在您不需要它们时使用它。

class YourCest
{
    private Faker\Generator $faker;
    private string $email;   

    public function __construct()
    {
        // "Run something" here
        $this->faker = Faker\Factory::create();
        $this->email = $this->faker->email;
    }
    
    public function __destruct()
    {
        // "and then clean it up" there
    }

    public function tryToTest(AcceptanceTester $I)
    {
        // Do your tests here
    }
}