如何使用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;
}
}
答案 0 :(得分:0)
对于void方法模拟使用EasyMock.expectLastCall()
例如,你想模拟
amimalService.saveOldAnimals(List<Animal> animals){} //present in AnimalService class
所以你的测试用例变成了
animalService.saveOldAnimals(animals);
EasyMock.expectLastCall();
你的虚空方法被嘲笑了。
在您的情况下,只需创建DeviceIdn对象并传递给getBoard方法。
getBoard(myDevice);
了解我们需要模拟什么,不知道什么。我不理解你的域类,所以无法帮助你。但是会帮助你理解需要模拟的东西。
例如,我有一个调用存储库说animalRepository.findByAge(int age)
,返回List<Animal>
现在假设你的getBoard()方法中有这个方法调用,所以你可以模拟那个方法,因为对于测试用例,从数据库中获取值是不好的。因此,每当调用存储库调用时,请准备自己的值并将其返回给方法。 所以嘲笑方法是这样的。
EasyMock.expect(animalRepository.findByAge(12)).andReturn(amimalsList);
这个animalsList是您自己在测试方法中准备的,以便让测试用例正常工作。