【问题标题】:Random String passed as the same string php随机字符串作为相同的字符串传递 php
【发布时间】:2018-03-04 01:22:03
【问题描述】:

尝试使用 PHP 和 Behat 创建功能测试,我想要一个随机字符串作为电子邮件,但我希望字符串在每次新测试运行时都是随机的,但我想将创建的相同字符串传递给不同的测试作为参数。

因此,如果我生成一个 10 位字符串,我想生成该字符串,然后将其作为相同的 10 位序列通过其他测试

我是 PHP 新手,所以我不太确定如何设置它,但这是我目前在 Behat 上下文文件中所拥有的内容

class FeatureContext implements Context {

private $MailPage;
private $registrationpage;


/**
 * Initializes context.
 *
 * Every scenario gets its own context instance.
 * You can also pass arbitrary arguments to the
 * context constructor through behat.yml.
 */
public function __construct(MailPage $mailPage, RegistrationPage $registrationpage)
{
    // Page obects injected directly in constructor with type hints.
    $this->MailPage = $MailPage;
    $this->registrationpage = $registrationpage;
}

/**
 * @BeforeSuite
 */
public static function  generateRandomString() {

    // Generate random string for Email implementation.
    $randomString = bin2hex(openssl_random_pseudo_bytes(10));
    return $randomString;

}


/**
 * @Given /^I register a temporary email address $/
 */
public function iRegisterATemporaryEmailAddress()
{
    $this->MailPage->grabNewEmail(self::generateRandomEmail());
}

/**
 * @Given /^I register a Developer account$/
 */
public function iRegisterADeveloperAccount()
{

    $this->registrationpage->fillInFormDetails(self::generateRandomEmail());
}

我遇到的问题是,在参数不变的情况下,每次调用它都会生成一个不同的字符串,但我只希望它为整个套件生成一次。有什么想法吗?

【问题讨论】:

  • 不完全确定我是否理解大局,但您可以在构造函数中分配 $this->randomString,然后简单地引用 randomString 属性而不是 generateRandomString 方法

标签: php string random parameters behat


【解决方案1】:

1- 从构造函数调用你的方法。

2- 使用this将生成的值保存在变量中

private $randomString ;
public function __construct(MailPage $mailPage, RegistrationPage $registrationpage)
{
   //your code
   $this->randomString = $this->generateRandomString();

}

3- 要使用此变量,您可以在类方法中调用它,例如 $this->randomString

具有构造方法的类在每个类上调用此方法 新创建的对象,因此它适用于任何初始化 对象在使用之前可能需要。

【讨论】:

  • 效果很好,最近才从 Java 迁移到 php,所以学习如何处理这些差异有时会让我彻底放屁。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
相关资源
最近更新 更多