java如何为函数编写junit测试用例
我在使用字符串重试机制的类中有一个方法。。 我的代码是:
@Override
@Retryable(
value={RuntimeException.class,IOException.class},
maxAttempts=3,
backoff=@Backoff(delay=5000)
)
public void sampleService(String payLoad, String type) throws HttpException, IOException
{
StringRequestEntity requestEntity = null;
PostMethod postMethod = new PostMethod();
HttpClient httpclient = new HttpClient();
InputStream inputStream = null;
int statusCode;
BufferedReader br = null;
String line;
StringBuffer eventResponse = new StringBuffer();
String jsonReceive = null;
try{
requestEntity = new StringRequestEntity(payLoad, MEDIA_TYPE, FORMAT);
if (type.equalsIgnoreCase("item")) {
postMethod = new PostMethod(baseServiceUrl + apiItemServiceUrl);
} else if (type.equalsIgnoreCase("itemGroup")) {
postMethod = new PostMethod(baseServiceUrl
+ apiItemGroupServiceUrl);
}
postMethod.setRequestEntity(requestEntity);
statusCode = httpclient.executeMethod(postMethod);
log.info("Status code from item service call: " + statusCode);
if (statusCode != 200) {
throw new Exception("Error in service call");
}
inputStream = postMethod.getResponseBodyAsStream();
if (null != inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream,
FORMAT));
for (line = br.readLine(); line != null; line = br.readLine()) {
eventResponse = eventResponse.append(line);
}
}
}
catch(Exception e){
log.info("Exception occurs " + e);
throw new RuntimeException(
"Exception occurs " + e);
}
jsonReceive = eventResponse.toString();
log.info("JsonReceive from the Service" + jsonReceive);
}
我想为上述方法编写Junit测试用例,当出现异常时,应该重试多次。有人能帮我写测试用例吗
# 1 楼答案
如果您使用的是JUnit,那么可以将return语句链接起来,使其在每次调用时都有不同的行为,例如: