2010-11-25 62 views
0

我最近开始使用单元测试,迄今为止一直是一个爆炸。测试夹具数据

但是,我遇到了一种情况,那就是我的方法显然是错误的,我无法将自己的头围绕在“好”的解决方案上。

该代码的上下文是查看用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'); 
} 

试验通信的方法的目的,但数据(夹具)测试在很大程度上依赖于什么数据中包含的假设。有没有更好的方法呢?

回答

0

这实际上并不是单元测试,因为您正在测试超出其边界的方法,请致电ChannelTable

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

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

要:

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

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

请记住,单元测试的目的是测试单元(方法),而不是别的。如果您的整个应用程序无法连接到数据库并提供数据,则单元测试仍会通过,因为该方法的行为应该与其应该一样。