【问题标题】:Testing fixture data测试夹具数据
【发布时间】:2010-11-25 20:04:23
【问题描述】:

我最近开始使用单元测试,到目前为止效果很好。

但是,我遇到了这样一种情况:我的方法完全错误,我无法找到一个“好的”解决方案。

代码的上下文是一个用 symfony 编写的用于查看电视广播时间表的应用程序,使用 sfPHPUnit2Plugin 进行了测试。

public function testLoadChannelBroadcasts() {

    $Start = new DateTime();
    $End = new DateTime();

    $Channels = ChannelTable::getChannelsWithBroadcastsTouchingTimeSpan($Start, $End);

    foreach ($Channels as $Channel) {
      $Channel->loadBroadcastsTouchingTimeSpan($Start, $End);
    }

    // test data

    $Broadcasts = $Channels[0]->Broadcasts;

    $assertion = $Broadcasts[0]->getDateTimeObject('start') <= $Start
     && $Broadcasts[0]->getDateTimeObject('end') >= $Start;

    $this->assertTrue($assertion, 'starts before scope, ends inside scope');

    $assertion = $Broadcasts[1]->getDateTimeObject('start') >= $Start
     && $Broadcasts[1]->getDateTimeObject('end') <= $End;

    $this->assertTrue($assertion, 'starts inside scope, ends inside scope');

    $assertion = $Broadcasts[2]->getDateTimeObject('start') >= $Start
     && $Broadcasts[2]->getDateTimeObject('end') >= $End;

    $this->assertTrue($assertion, 'starts inside scope, ends outside scope');

    $LongBroadcast = $Channels[1]->Broadcasts[0];

    $assertion = $LongBroadcast->getDateTimeObject('start') <= $Start
     && $LongBroadcast->getDateTimeObject('end') >= $End;

    $this->assertTrue($assertion, 'starts before scope, ends after scope');
}

测试传达了方法的目的,但数据(夹具)的测试在很大程度上依赖于对数据包含什么的假设。有更好的方法吗?

【问题讨论】:

    标签: php unit-testing symfony1 phpunit


    【解决方案1】:

    这并不是真正的单元测试,因为您正在通过调用ChannelTable 在其边界之外测试方法。

    这样做的正确方法是改变:

    $Channels = ChannelTable::getChannelsWithBroadcastsTouchingTimeSpan($Start, $End);
    

    收件人:

    $Channels = array('yourdata', 'etc');
    

    这样,如果ChannelTable 未能提供正确的数据,您的测试不会失败,因为它不应该失败。

    请记住,单元测试的目的是测试单元(方法),仅此而已。如果您的整个应用程序无法连接到数据库并提供数据,单元测试仍然可以通过,因为该方法的行为正常。

    【讨论】:

      猜你喜欢
      • 2011-06-07
      • 1970-01-01
      • 2022-06-17
      • 1970-01-01
      • 2018-02-03
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      相关资源
      最近更新 更多