gpt4 book ai didi

php - 这个 PHPUnit 测试是否有意义(或者我正在测试框架/PHP)?

转载 作者:可可西里 更新时间:2023-10-31 23:32:59 24 4
gpt4 key购买 nike

我刚刚开始使用 PHPUnit 和 TDD。

除其他外,我无法真正回答这个问题:这是一个很好的测试吗?我实际上是在测试我的代码还是已经测试过的东西(即框架或 PHP 本身)?

小例子,这是测试对象:

class DateMax extends Constraint
{
/**
* @var string
*/
public $limit;

/**
* @var string
*/
private $invalidLimit = 'Option "limit" should be a valid date/time string.';

public function __construct($options = null)
{
parent::__construct($options);

if(false === strtotime($this->limit)) {
throw new InvalidOptionsException($this->invalidLimit, ['limit']);
}
}
}

我想测试当传递无效的“limit”选项时,InvalidOptionsException 是预期的,否则 $constraint->limit 保持正确的值:

/**
* @dataProvider getInvalidLimits
* @expectedException InvalidOptionsException
*/
public function testInvalidLimits($testLimit)
{
new DateMax($testLimit);
}

/**
* @dataProvider getValidLimits
*/
public function testValidLimits($testLimit)
{
$constraint = new DateMax($testLimit);
$this->assertEquals($testLimit, $constraint->limit);
}

/**
* @return array[]
*/
public function getInvalidLimits()
{
return array(array('invalid specification'), array('tomorr'));
}

/**
* @return array[]
*/
public function getValidLimits()
{
return array(array('now'), array('+1 day'),array('last Monday'));
}

所以问题是这是否有意义,或者我正在测试框架/PHP 本身?

最佳答案

当然它是有道理的,因为你覆盖了 Constraint 类的构造函数并且有可能你会破坏它里面的东西。因此,基于您的构造函数逻辑,您基本上想要测试两件事:

  1. 检查你是否使用相同的选项调用父级的构造函数,恰好一次(你可以为此目的使用模拟,你不关心设置适当的限制值,因为这应该在约束类中测试)
  2. 检查当 limit 有错误的值(例如 null)时是否抛出了适当的异常

编辑:第一个测试有用的一些用例可能是这个:

假设在某个时候您想以这种方式扩展 DateMax 构造函数:

public function __construct($options = null)
{
$this->optionsWithDecrementedValues = $this->doWeirdThings($options);

parent::__construct($options);

if(false === strtotime($this->limit)) {
throw new InvalidOptionsException($this->invalidLimit, ['limit']);
}
}

但是例如您没有注意到方法“doWeirdThings”将引用作为参数。所以实际上它改变了 $options 值,这是你没有想到的,但第一次测试失败所以你不会错过它。

关于php - 这个 PHPUnit 测试是否有意义(或者我正在测试框架/PHP)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12526763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com