Mockito:如何模拟在另一个方法中调用的方法



我是mockito的新手,我正在使用mockito来测试调用另一个方法并调用方法返回字符串的方法。我试过了,但我无法写测试。请帮忙

public class MyClass {
  protected String processIncominData(String input) {
    String request = ...;
    ...
    String response = forwardRequest(request);
    ...
    return response;
  }
  public String forwardRequest(String requestToSocket) {
   String hostname = socketServerName;
    int port = socketServerPort;
    String responseLine=null;
    Socket clientSocket = null;  
    PrintStream outs=null;
    BufferedReader is = null;
    BufferedWriter bwriter=null;
    try {
        clientSocket = new Socket(hostname, port);
        outs=new PrintStream(clientSocket.getOutputStream());
        is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        bwriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
    } catch (UnknownHostException e) {
        LOGGER.error("Don't know about host: " + hostname + e.getMessage());
    } catch (IOException e) {
        LOGGER.error("Couldn't get I/O for the connection to: " + hostname + e.getMessage());
    }
    if (clientSocket == null || outs == null || is == null) {
        LOGGER.error("Something is wrong. One variable is null.");
    }
    try {
        while ( true ) {
            StringBuilder sb = new StringBuilder();
            sb.append(requestToSocket);
            String  request = sb.toString().trim();
            bwriter.write(request);
            bwriter.write("rn");
            bwriter.flush();
            responseLine = is.readLine();
            LOGGER.info("Socket returns : " + responseLine);
            //outs.println(responseLine);
            bwriter.close();
        }
    } catch (UnknownHostException e) {
        LOGGER.error("Trying to connect to unknown host: "+ e.getMessage());
    } catch (IOException e) {
        LOGGER.error("IOException:  "+ e.getMessage());
    }
    finally{
        try {
            outs.close();
            is.close();
            clientSocket.close(); 
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return responseLine;
  }
}

我想在这里模拟xml响应以测试processIncomingData方法。此响应来自套接字服务器,我正在通过套接字客户端发送请求。我认为如果我可以从套接字模拟 xmlResponse ,套接字就无关紧要了。请给出任何有用的答案

现在你已经发布了它,如何模拟它的答案就在这里。

testing-java-sockets

您可以尝试spy方法:

MyClass myClass = spy(new MyClass());
when(myClass.forwardRequest("foo")).thenReturn("bar");

然后当你打电话

myClass.processIncominData("baz");

响应将为"bar"(如果请求为"foo")

PS:当你需要模拟被测类时,它表明你的设计存在一些问题。

相关内容

  • 没有找到相关文章

最新更新