2013-12-16 33 views
0

如何使用EasyMock爲getBoards方法編寫JUnit(下面在示例中提到)。我試過但無法通過在EasyMock中使用JUnit來覆蓋代碼。我已經簡單多了一個環節「https://stackoverflow.com/questions/20604031/how-to-write-test-method-for-void-method-in-junit-easymock-in-javalittle-diff-i如何在java中使用easymock編寫junit?

public class DCI implements ...{ 
private Device device = null; 
    private SnmpUtils snmp = null; 
DCM(Device device){ 
this.device = device; 
} 

@override 
void openCommun(){ 
snmp = new SnmpUtils(device); 
snmp.openSnmpComm(); 

} 
// ---> How to write Junit test with easymock for this method? 
public List<Board> getBoards(DeviceIdn deviceIdn) throws SnmpException { 

     List<Board> boardList = new ArrayList<Board>(); 
     try { 
     //BoardTableClass --> Below given 
      BoardTable boardTable = new BoardTable(snmp); 
      boardTable.readTable(); 

      for (int row = 0; row < boardTable.size(); row++) { 

       String strBoardIndex = boardTable.getValue(row, BoardTable.BoardColumn.BoardIndex); 
       String strBoardName = boardTable.getValue(row, BoardTable.BoardColumn.BoardName); 
       String strBoardType = boardTable.getValue(row, BoardTable.BoardColumn.BoardType); 
       int boardIndex = new Integer(strBoardIndex); 
       BoardIdn boardIdn = new BoardIdn(deviceIdn, boardIndex); 
       Board board = new Board(boardIdn); 
       board.setName(strBoardName); 
       board.setType(strBoardType); 
       boardList.add(board); 
      } 
      logger.info(boardList.size()); 
     } 
     //In handleException method , snmpException checked 
     catch (Exception e) { 
      handleException(e); 
     } 

     return boardList; 
    } 
} 
+0

這種佈局並不完全有利於嘲笑。你將一個實例變量傳遞給你正在構建的對象。除非你想模擬實例變量,否則嘲笑實際上很少。 – Makoto

+0

嗨,謝謝。但是哪一個在這裏嘲笑.. – shree

回答

0

解釋爲無效方法嘲諷使用EasyMock.expectLastCall()

例如你想嘲笑

amimalService.saveOldAnimals(List<Animal> animals){} //present in AnimalService class 

所以,你的測試用例變得

animalService.saveOldAnimals(animals); 
EasyMock.expectLastCall(); 

你的虛空方法被嘲笑。

你的情況,只需創建DeviceIdn對象並傳遞給getBoard方法。

getBoard(myDevice); 

明白我們需要模擬什麼not.I我不理解你的域類,從而無法幫助you.But將幫助您瞭解什麼需要模擬。

例如,我有一種調用庫說animalRepository.findByAge(int age)其返回List<Animal>

現在,在您getBoard假設()方法,如果你有這樣的方法調用,所以你可以嘲笑這種方法,因爲測試情況下,它是不是好從數據庫中獲取值。因此,只要調用存儲庫調用,準備自己的值並將其返回給方法。 所以嘲笑方法就是這樣。

EasyMock.expect(animalRepository.findByAge(12)).andReturn(amimalsList); 

這個animalsList是你自己在你的測試方法中編寫的,以便讓測試用例工作。

+0

No ..getBoards方法不是void method.it返回List ..我試過了,但在第二步,它的出來,它根本不在裏面 – shree

+0

No ..getBoards方法不是無效method.it返回List..i嘗試,但在第二步,它的出來,它根本不在裏面..BoardTable boardTable = new BoardTable(snmp); boardTable.readTable();在此之後它出來 – shree

+0

這就是爲什麼我問你什麼BoardTable和你得到什麼錯誤。我無法提供幫助,因爲我不知道您的域名類 –

相關問題