2013-12-12 103 views
0

我无法写EasyMock的或期待无效methods.I想写诗的Board.Please任何人的帮助测试类that..my类这样将在下文如何在java中的junit easymock中编写void方法的测试方法?

public class Board{ 
    Snmp snmp; 
    Board(Snmp snmp){ 
    this.snmp = new Snmp(); 
    } 
    private void readTable() throws SnmpException { 
      ArrayList<String> boardOIDs = new ArrayList<String>(); 
      List<List<String>> valuesList = new ArrayList<List<String>>(); 
      List<List<String>> oidsList = new ArrayList<List<String>>(); 

      boardOIDs.add(OID_BOARD_INDEX); 
      boardOIDs.add(OID_BOARDNAME); 
      boardOIDs.add(OID_BOARDTYPE); 

      //this method read and put value into valueList 
      snmp.snmpGetTable(boardOIDs, oidsList,valuesList); 

      s.o.p("Value List size" +valuesList.size); 

    }  
    } 

回答

1

你可以训练模拟给定使用一个答案:

@Test 
public void testReadTable() { 
    Snmp snmp = createMock(Snmp.class); 
    snmp.snmpGetTable(anyObject(List.class), anyObject(List.class), anyObject(List.class)); 

    IAnswer answer = new IAnswer() { 

     @Override 
     public Object answer() throws Throwable { 
      List list = (List) getCurrentArguments()[2]; 
      list.add("a"); 
      return null; 
     } 
    }; 

    expectLastCall().andAnswer(answer); 
    replay(snmp); 

    Board board = new Board(snmp); 
    board.readTable(); 

    verify(snmp); 
} 

请注意,你需要修复你的板类的构造函数,使该方法至少默认可见或调用它以任何其他方式。

... 
Board(Snmp snmp){ 
    this.snmp = snmp; 
} 

void readTable(){ 
... 

又见这样的回答:easymock-void-methods

+0

我想模拟snmp..and我想写testValueListSize()..但是snmp类是第三方源代码..i写道测试case.but价值清单大小总是为零达到 – shree

+0

只是澄清:你想嘲笑方法'snmpGetTable',并期望变量'valuesList'不是空的? – Spindizzy

+0

不是。那是已经被嘲笑的第三方源代码方法Creatmock(Snmp.class);但是在添加之后,我在'snmpGetTable'中获得了空值。 – shree

0

可能,如果你想查询的输出结果。

但是,您的方法并非设计为允许轻松捕获输出,因为您不会传入输出流。不过,你可以模拟System.out.println,并确保它得到正确的参数。

2

您的构造函数不使用snmp实例中的传递,而是创建一个新的实例。你为什么这样做?

Board(Snmp snmp){ 
    this.snmp = new Snmp(); 
} 

应该

Board(Snmp snmp){ 
    this.snmp = snmp; 
} 

然后你就可以使用了EasyMock创建一个模拟Snmp实例,并把它传递给Board的构造。

Snmp mock = createMock(Snmp.class); 

Board board = new Board(mock); 

指望在EasyMock的无效方法,你并不需要使用expect方法。当模拟处于重放状态时,只需在模拟上调用该方法即可。

因此,要指望snmpGetTable()呼叫你刚才说

ArrayList<String> boardOIDs = ... 
List<List<String>> valuesList =... 
List<List<String>> oidsList = ... 

Snmp mock = createMock(Snmp.class); 

//this is the expectation 
mock.snmpGetTable(boardOIDs, oidsList,valuesList); 
//now replay the mock 
replay(mock); 

Board board = new Board(mock); 

如果您需要抛出从一个void方法的异常可以用easymock'sexpectLastCall()

//this is the expectation 
mock.snmpGetTable(boardOIDs, oidsList,valuesList); 

expectLastCall().andThrow(new Exception(...)); 

Easymock documentation了解更多详情