Mockito: How to mock a method called inside another method

I am new to mockito and I use mockito to test a method that calls another method and the method returns a string. I tried, but I can not write a test. Please, help

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 the xml answer here to test the processIncomingData method. This response comes from the socket server, and I send the request to the socket client. I think the socket doesn't matter if I can mock xmlResponse from the socket. Please give a helpful answer.

+3
source share
2 answers

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

testing-java-sockets

+1

spy .

MyCalss my = spy(new MyCalss());
when(my.forwardRequest("foo")).thenReturn("bar");

,

my.processIncominData("baz");

"bar" ( "foo" )

PS: , .

0

Source: https://habr.com/ru/post/1583810/


All Articles