2

如果时间戳是周末,即星期六或星期日,我有一个小方法返回真或假。

现在我对单元测试非常陌生,我正在尝试为此编写单元测试。

在我的测试用例中,我将如何进行:

这是我的初步想法。

1. Pick any 1 week from the past and then...
   1.1. Get a timestamp for all 5 week days (mon through fri) and pass each timestamp to the function being tested.  If they all return false then proceed...
   1.2  Get the timestamp for both weekend days and pass each to function being tested.  If they both return true then we know the function is correct.

或者

2  Simply pick 1 weekday from the past and 1 weekend day from the past and test with only those 2 dates

我在这两种方法中是否正确,还是有更好的方法来测试它?

4

2 回答 2

2

这需要一两个数据提供者。PHPUnit 将首先调用数据提供者来获取一个数组,其中包含它将传递给测试的数据集,其中每个数据集都是要传递给测试方法的参数数组。接下来,它对每个数据集执行一次测试。在这里,每个数据集都是一个简单的日期字符串以及错误消息的日期名称。

/**
 * @dataProvider weekdays
 */
function testDetectsWeekdays($date, $day) {
    self::assertTrue($fixture->isWeekday($date), $day);
}

/**
 * @dataProvider weekends
 */
function testDetectsWeekends($date, $day) {
    self::assertFalse($fixture->isWeekday($date), $day);
}

function weekdays() {
    return array(
        array('2012-08-20', 'Monday'),
        array('2012-08-21', 'Tuesday'),
        array('2012-08-22', 'Wednesday'),
        array('2012-08-23', 'Thursday'),
        array('2012-08-24', 'Friday'),
    );
}

function weekends() {
    return array(
        array('2012-08-25', 'Saturday'),
        array('2012-08-26', 'Sunday'),
    );
}

至于测试的日期,您需要考虑在您的课程中可能出现的任何极端情况。闰年会影响吗?时区?这取决于作为单元(白盒)测试一部分的实现。

于 2012-08-25T19:28:06.770 回答
1

如果您将多个检查放入一个测试中,您将遇到一个问题,即当第一个检查失败时,您将不知道某些检查可能会返回什么。假设该方法在第 3 天失败。第 4 天可以用吗?在尝试查找错误时,此信息可能非常有用。

我的方法是一次测试所有值。它是这样工作的:

  1. 选择过去的日期
  2. 创建一个循环,将日期提前一天 8 次
  3. 为每个日期调用方法并将结果附加到字符串
  4. 通过查看真实日历创建具有预期结果的字符串)
  5. 比较两个字符串

这样,您可以一眼看出该方法失败的日期。

另一种选择是编写 8 个测试并让每个测试检查一个日期。

提示:当引入时区时,这样的测试往往会失败。创建更多使用接近午夜的时间戳并使用 timezome 的测试。结果仍然正确吗?

于 2012-08-24T12:25:18.487 回答