我是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("\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;
}
}
我想在這裏嘲笑XML響應測試processIncomingData method..This響應從套接字服務器未來,我通過發送套接字客戶端請求。我認爲套接字不會影響,如果我可以從套接字模擬xmlResponse。請給出任何有用的答案
顯示如何'正在生成xmlResponse'。您需要在'String xmlResponse = ...;'行使用模擬。如果這是一個實例方法調用,使用'Mockito'來模擬bean(讀取套接字客戶端)。如果這是一個靜態調用,使用'JMockit'來模擬靜態調用。 – 2014-11-25 12:42:43
我正在閱讀來自套接字服務器的xml響應。它是字符串格式,如「 」etc –
Lakshya
2014-11-25 13:17:12
你的單元測試不應該依賴套接字服務器。你應該嘲笑客戶。 – 2014-11-25 13:28:40