【问题标题】:Does this PHPUnit test make any sense (or I'm testing the framework/PHP)?这个 PHPUnit 测试是否有意义(或者我正在测试框架/PHP)?
【发布时间】:2012-09-21 08:21:37
【问题描述】:

我只是从 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']);
        }
    }
}

我想测试当通过无效的“限制”选项时,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 本身?

【问题讨论】:

    标签: php unit-testing testing phpunit


    【解决方案1】:

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

    1. 检查您是否使用相同的选项调用父级的构造函数,仅一次(您可以为此使用模拟,您不需要设置适当的限制值,因为这应该在约束类中进行测试)
    2. 检查限制值错误时是否引发了适当的异常(例如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 的值,这是你没想到的,但是第一次测试失败了,所以你不会错过它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 2019-11-10
      • 2011-12-16
      • 1970-01-01
      • 2014-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多