![](/img/trans.png)
[英]Scala/Mockito: How to mock the result of a method called inside another method?
[英]Mockito:How to mock method called inside another method
我是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方法..這個響應來自套接字服務器,我正在通過套接字客戶端發送請求。 我認為如果我可以從socket模擬xmlResponse,套接字無關緊要。 請給出任何有用的答案
你可以試試spy
方法:
MyClass myClass = spy(new MyClass());
when(myClass.forwardRequest("foo")).thenReturn("bar");
然后當你打電話
myClass.processIncominData("baz");
響應將是“bar”(如果請求是“foo”)
PS:當你需要模擬測試類時,它會顯示你的設計有些問題。
現在您已經發布了它,如何模擬它的答案就在這里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.