我正在尝试对我定义的用于检查连接并将任何文档发布到API的某些方法使用嘲笑fwk。由于我是模拟迷的新手,所以我几乎不知道该如何计划我的考试计划
我刚刚使用assertEquals尝试了模拟的基础知识,但是我想知道如何更好地模拟我的场景。在下面的类中,类A使用HTTPSUrlConnection并仅检查连接是否成功,而在类B中,其类使用类A连接对象的方法尝试将文档发送到API。现在,我该如何模拟这种情况。
class A{
public void checkConnection(){
HttpsURLConnection con = null;
URL url = null;
try {
url = new URL(endPoint); //endpoint gets the value from properties file at runtime
} catch (MalformedURLException e) {
}
try {
con = (HttpsURLConnection) url.openConnection();
} catch (IOException e) {
}
String userpass = userName + ":" + password; //gets the value from properties file at runtime
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
con.setRequestProperty("Authorization", basicAuth);
con.setDoInput(true);
con.setDoOutput(true);
try {
con.setRequestMethod("POST");
} catch (ProtocolException e) {
}
}
}
class B{
public String send(){
String responseBody = null;
SenderResponse senderResponse = null;
try {
Resource r = new ClassPathResource("xslt.xsl");
File f = null;
f = new File(r.getURL().getPath());
Source xs = new StreamSource(f);
Resource r1 = new ClassPathResource("input.xml");
File f1 = null;
f1 = new File(r1.getURL().getPath());
Source xml = new StreamSource(f1)
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer trans = tf.newTransformer(xs);
StringWriter stringWriter = new StringWriter();
Result res = new StreamResult(stringWriter);
trans.transform(xml, res);
String result = stringWriter.toString();
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(result);
writer.flush();
writer.close();
if (HttpStatus.OK.value() == con.getResponseCode()) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
responseBody = response.toString();
} else {
}
} catch (TransformerFactoryConfigurationError | TransformerException e) {
} catch (ParserConfigurationException e) {
} catch (SAXException e) {
} catch (IOException e) {
}
catch (Exception e) {
}
return responseBody;
}
}
我只想使用这两个类中定义的现有方法,而不是编写模拟代码