2010-11-24 265 views
2

的出口如何單元測試下面的代碼段:如何單元測試即時方法

 
@Override 
public void update() { 
    if (isStopped() || isPaused()) { 
    return; 
    } 
    // ... 
} 

該方法是從一個音頻流。它需要定期調用,以便流讀取新數據。如果播放停止或暫停,則流不應前進,因此我立即返回。但是,我找不到爲此代碼編寫測試的方法。

+0

我們需要看到更多的代碼作爲方法的變化沒有明顯的狀態 - 這樣什麼樣的實例變量在那裏,什麼是停止和isPaused呢? – Mark 2010-11-24 22:29:22

回答

1

也許會返回一個boolean表示發生了什麼?

1

在這種情況下,您應該測試方法調用沒有副作用。例如,如果......在協作者上有方法調用,則應該嘲笑該協作者,然後驗證協調者上沒有方法被調用。

您可能還可以測試其上更新被稱爲沒有改變,這取決於究竟是你們班對象的屬性....

0

這裏有一個複雜的方法:

一個想法是實現Observer模式,定義一個偵聽器接口,可以訂閱來自您的測試類的事件。

public interface EventListener{ 
    // EventDetails would be an object that encapsulates 
    // event type and extra data 
    void process(EventDetails type); 
} 


private void dispatchEvent(EventType type){ 
    for(EventListener listener : this.listeners){ 
     listener.process(new EventDetails(type 
      /* you'll want to add more data than that here */)); 
    } 
} 


@Override 
public void update() { 
    if (isStopped() || isPaused()) { 
    return; 
    } 
    dispatchEvent(EventType.UPDATE); 
    // ... 
} 

而且在測試類:事件會在這種情況下,如果塊後發送

yourClass.addEventListener(new EventListener(){ 
    public void process(EventDetails details){ 
     if(EventType.UPDATE.equals(details.getEventType())){ 
      fail("Received update event"); 
     } 
    } 
}); 
// set to stopped or paused 
yourClass.update(); 
// if we got here, test has succeeded 

當然,這種做法是一個巨大的侵入事情現在正在努力的方式,它只有在你的應用程序可以使用事件通知系統時纔有意義(單元測試功能只是一個很好的副作用)。


或者完全不同的東西:

在單元測試

,使用覆蓋任何方法,如果塊之後被稱爲子類。

所以我們說原來的代碼是這樣的:

@Override 
public void update() { 
    if (isStopped() || isPaused()) { 
    return; 
    } 
    doUpdate(); 
} 

那麼子類將覆蓋doUpdate()方法:

protected void doUpdate(){ 
    fail("I shouldn't be here"); 
}