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测试用例,发生异常时应重试多次。有人可以帮我编写测试用例吗?
解决方案
如果您使用的是 JUnit,则可以链接 return 语句以在每次调用时具有不同的行为,例如:
when(httpclient.executeMethod(postMethod))
.thenReturn(errorCode)
.thenReturn(anotherErrorCode)
.thenReturn(200)
推荐阅读
- pandas - 数据框按数值列分组,然后与原始数据框组合
- c++ - C++ 如何为自己的迭代器类从迭代器转换为 const_iterator?
- android - 在android的媒体播放器中添加回声效果
- python - 尝试使用 OneHotEncoder 结果创建数据帧时出现 ValueError
- sql - 即使没有关联的行,SQL如何从加入其他表的表中选择所有行
- mysql - 如何使用 Sequelize 添加外键和级联属性?
- python - 修补单元测试中的单个类方法并断言它被调用一次
- python - 卡恩算法的顺序不正确
- html - 设置类型为 number 的 Input 字段所需的确切元素数量
- rest - Delphi:带有基本身份验证的 REST 请求