使用mockito,powermock模拟调用另一种方法的方法

时间:2016-10-03 07:36:55

标签: java unit-testing mockito powermockito

- > controller.java

public controller() {
    public controller(DataInterpreter interpret,ControllerClientUtility util, InterfaceConnection inter) {
        interpreter = interpret;
        utility = util;
        interfaced = inter;
    }
}

...

public void closeOne(String vpnSessionId) throws Exception {
        try{
            if ( interfaced.connect() && (interfaced.CheckIntegrity(SessionId)) ){
                interfaced.kill(vpnSessionId);
            }else{
                closeAll();
            }
        }catch(Exception e){
            if ( e.getMessage().startsWith("INTERFACE_ERR:") ){
                closeAll();
            }else{
                throw new Exception(e);
            }
        }
    }

- > InterfaceConnection.java中的方法

public String getReponseFor(String command) throws Exception{
    if (send(command)){
        return receive();
    }
    else{
        throw new Exception("INTERFACE_ERR: Could not get Response");
    }
}


public List<String> getListOfConnections() throws Exception{
   String statusResponse = getReponseFor("something");
   ..(regex searches and then make a list connectionsConnected) 
   return connectionsConnected;
}


public boolean CheckIntegrity(String SessionId){
    try {
        List<String> connections = new ArrayList<String>();
        connections = getListOfConnections();
        if (connections.contains(SessionId)){
            return true;
        }
        return false;
    }catch(Exception e){
        return false;
    }
}

有没有办法模拟getListOfConnections的输出?我尝试做过这样的事情,但没有工作

- &GT; controllerTest.java

 @Mock private InterfaceConnection interfaced;

  @Before
  public void beforeTests() throws Exception {
    MockitoAnnotations.initMocks(this);
    impl = new Controller(interpreter,utility,interfaced);

...

@Test
  public void testDisconnectOneSessionWithBadSessionId_sendCommand() throws Exception{
      String badSessionId = "123:123";
      List<String> mockConnections = new ArrayList<String>();
      mockConnections.add("asdasds");
      when(interfaced.getListOfConnections()).thenReturn(mockConnections);

      impl.closeOne(badSessionId);
      Mockito.verify(utility)....
 }

我希望我能在此事先明确表示。

0 个答案:

没有答案
相关问题