【发布时间】:2013-12-16 14:57:44
【问题描述】:
如何使用 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”中简要解释了
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;
}
}
【问题讨论】:
-
这种布局不利于模拟。您正在将实例变量传递给您正在具体构建的对象。除非您想模拟实例变量,否则与模拟几乎没有关系。