2013-02-25 128 views
0

我正在研究Junit測試案例,評分方案基於代碼的覆蓋範圍。 我遇到了一個關於某個方法內部的@override方法的問題,因爲它看起來像我不能調用該方法。 就像下面的例子。關於@override方法的junit測試案例

public void showFollowersList(PagableResponseList<User> followers) { 
    m_itemList.addListener(SWT.Resize, new Listener() { 
    @Override 
    public void handleEvent(Event arg0) { 
    m_itemList.setLayoutData(new RowData(m_itemList.getBounds().width, 
             m_itemList.getBounds().height)); 
    m_rightFrame.layout(); 
    m_rightFrame.pack(); 
    } 
}); 
} 

addMouseTrackListener(new MouseTrackListener() { 
    @Override 
    public void mouseHover(MouseEvent arg0) { 
    } 

    @Override 
    public void mouseExit(MouseEvent arg0) { 
    Rectangle rect = HoverClickableComposite.this.getClientArea(); 
    if (!m_clicked && !rect.contains(arg0.x, arg0.y)) { 
     setBackground(m_origColor); 
    } 
    } 

如何調用或覆蓋handleEvent,mouseExit和mouseHover等方法?

回答

0

如果有幫助,我認爲有人做了非常好的工作,使showFollowersList不可測試。那是故意的嗎?

如果是的話,正確的答案可能不是實際上是一組測試代碼,而是一個非常覆蓋率低的分數和改變類,使之更容易測試的建議清單...

的唯一途徑現在測試它將會是設置,捅它,並檢查發生了什麼。 如果你能導致handleEvent呼叫只會工作要在對象上解僱,某些方法是可用的類:getListgetListenerCount等。然後,像:

testObject.showFollowersList(followers); 
// All that method does is add listener. So check that listener got added 
assertEquals(1, testObject.getList().getListenerCount()); 

// Now check that inner handlers behave correctly 
testObject.getList().fireEvent(); 
// This should have created a new RowData in the list 
assertNotNull(testObject.getList().getLayoutData()); 

但是,如果你不要有這些方法可用,那麼添加它們並公開List只是爲了單元測試的目的不是一個好主意。

另一個問題是GUI。你的單元測試將沒有GUI。因此,您的m_rightFrame可能會爲空(即使它不是,底層AWT類將是)。

0

它不是'方法內部'的方法,它是匿名類的方法。

通常情況下,用SWT和Swing編程,它是代碼的功能(業務)方面,需要很多的測試覆蓋率,而不是腳手架(處理器等)

但是,如果這是需要什麼,至少有兩個選項 -

  1. 不要對處理程序使用匿名內部類 - 在同一個包中給它們起一個名稱。
  2. 使用一個像Powermock一樣的模擬框架和JUnit,並傳遞模擬的SWT事件對象來調用處理程序,以便覆蓋範圍。