[英]How to write junit with easymock in java?
如何使用EasyMock編寫用於getBoards方法的JUnit(在下面的示例中進行了介紹)。我嘗試但無法通過將JUnit與EasyMock一起使用覆蓋代碼。 我已經在另一個鏈接中簡要說明了“ https://stackoverflow.com/questions/20604031/how-to-write-test-method-for-void-method-in-junit-easymock-in-javalittle-diff-i ”
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;
}
}
對於void方法模擬,請使用EasyMock.expectLastCall()
例如你想嘲笑
amimalService.saveOldAnimals(List<Animal> animals){} //present in AnimalService class
所以你的測試用例變成
animalService.saveOldAnimals(animals);
EasyMock.expectLastCall();
您的void方法已被嘲笑。
在您的情況下,只需創建DeviceIdn對象並傳遞給getBoard方法即可。
getBoard(myDevice);
了解我們需要模擬的內容和不需要的東西。我不了解您的域類,因此無法幫助您,但將幫助您了解需要模擬的內容。
例如,我有一個調用存儲庫的文件,例如animalRepository.findByAge(int age)
,它返回List<Animal>
現在假設在您的getBoard()方法中是否有此方法調用,以便可以模擬該方法,因為對於測試用例,從數據庫中獲取值不是很好。 因此,請准備您自己的值,並在每次調用存儲庫調用時將其返回給方法。 因此,模擬方法就是這樣。
EasyMock.expect(animalRepository.findByAge(12)).andReturn(amimalsList);
為了使測試用例正常工作,您自己在測試方法中准備了此動物列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.