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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27126510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:51:17  来源:igfitidea点击:

Mockito:How to mock method called inside another method

javajunitmockito

提问by Lakshya

I am new to mockito and I am using mockito to test method which is calling another method and called method returns string. I tried but I am unable write test. Please help

我是 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("\r\n");
            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;
  }
}

I want to mock xml response here to test processIncomingData method..This response is coming from socket server and I am sending request by socket client. I think socket will not matter if I can mock xmlResponse from socket. Please give any helpful answer

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

采纳答案by John B

Now that you have posted it, the answer to how to mock it is here.

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

testing-java-sockets

测试-java-sockets

回答by talex

You can try the spymethod:

你可以试试这个spy方法:

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

then when you call

然后当你打电话

myClass.processIncominData("baz");

the response will be "bar" (if request is "foo")

响应将是“bar”(如果请求是“foo”)

PS: When you need to mock class under test it shows some problem with your design.

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