2014-06-09 93 views
0

我想測試服務器是否會返回字符串。但是,我想測試它而不實際連接到服務器。我試圖擺脫通過嘲笑服務器的java.net.SocketException。我應該怎麼做?使用Mockito模擬服務器

下面的代碼聲明瞭服務器的所有必需值。

@RunWith(MockitoJUnitRunner.class) 
public class testTransfer { 



@Test 
public void getServerMessage() { 
    //variables 
    String serverhostname = "serverA"; 
    int portNo = 8888; 
    int versionNo = 9999; 
    String protocol = "tcp"; 
    String serverInput = "input string"; 

    String url = "http://localhost:8080/server/url"; 


    Service service =new Service(); 
    Call call = Mockito.mock(Call.class); 
    server_string result = Mockito.mock(server_string.class); 

以下代碼調用服務器並在xml中添加值。

//try catch 
     try { 

     call=(Call)service.createCall(); 
     QName qn = new QName("urn:ServerApiService", "server_string"); 
     call.registerTypeMapping(server_string.class, qn, 
       new org.apache.axis.encoding.ser.BeanSerializerFactory(server_string.class, qn), 
       new org.apache.axis.encoding.ser.BeanDeserializerFactory(server_string.class, qn)); 

     call.setTargetEndpointAddress(new java.net.URL(url)); 
     call.addParameter("arg1", XMLType.XSD_STRING, ParameterMode.IN); 
     call.addParameter("arg2", XMLType.XSD_INT, ParameterMode.IN); 
     call.addParameter("arg3", XMLType.XSD_INT, ParameterMode.IN); 
     call.addParameter("arg4", XMLType.XSD_STRING, ParameterMode.IN); 
     call.addParameter("arg5", XMLType.XSD_STRING, ParameterMode.IN); 
     call.addParameter("arg6", qn, ParameterMode.OUT); 
     call.setOperationName(new QName(url, "getServerMessage")); 
     call.setReturnClass(server_string.class); 
     //result = (server_string) call.invoke(new Object[] {serverhostname,portNo,versionNo,protocol,serverInput}); 
     result = (server_string) Mockito.when(call.invoke(new Object[] {serverhostname,portNo,versionNo,protocol,serverInput})).thenReturn(server_string.class); 
     System.out.println("Get server_string object from server ...."); 
        // System.out.println("Value is "+result.value); 
    } catch (ServiceException e) { 
     e.printStackTrace(); 
    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (RemoteException e) { 
     e.printStackTrace(); 
    } 


} 

} 

不過,我不斷收到這個

AxisFault 
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException 
faultSubcode: 
faultString: java.net.SocketException: Connection reset 
faultActor: 
faultNode: 
faultDetail: 
    {http://xml.apache.org/axis/}stackTrace:java.net.SocketException: Connection reset 
+0

你在測試什麼?你是否試圖嘲笑服務器的結果?這裏有很多相互依賴的代碼,所以我不能100%清楚你想要測試的是什麼。 – Makoto

+0

@Makoto是的,我試圖從服務器嘲笑結果。 – user3720852

回答

1

我用wiremock,效果良好。這是專門爲這項工作設計的模擬框架。

0

您也可以使用JBoss並運行該項目。當嘲笑服務器時,你需要使用@Bohemian所說的內容,因爲它更容易。然而,學習曲線很高,不建議在緊急情況下(我是一個新手btw)。