我应该如何为getUrl方法编写测试?
public class UrlList {
private final String[] urls;
private int index;
private SecureRandom random;
public static enum Mode {
VALUE_1,
VALUE_2,
VALUE_3;
}
public UrlList(String... urls) {
if (urls == null || urls.length == 0) {
throw new IllegalArgumentException("The url list may bot be null or empty!");
}
this.urls = urls;
this.index = 0;
this.random = new SecureRandom();
}
public String getUrl(Mode mode) {
switch (mode) {
case VALUE_1:
return urls[0];
case VALUE_2:
return urls[random.nextInt(urls.length)];
case VALUE_3:
try {
return urls[index];
} finally {
index = (index + 1) % urls.length;
}
default:
throw new RuntimeException("Unknown mode!");
}
}
}在上面的代码中,urls是一个字符串数组。
主要问题是我应该如何测试case VALUE_3:
因为第一次测试index = 0时,index的值将更改为finally块中的其他值,我希望在同一个单元测试类中使用新的index值再次测试它。
发布于 2014-06-18 20:11:03
您是否考虑过为每个测试方法创建一个新的类实例(封装索引和getUrl的实例)?因此,每种测试方法都是从index=0开始的。
发布于 2014-06-18 20:56:24
对于您的测试,您必须能够将私有index变量的值设置为(例如):
获得一个正值并且小于一个值来控制你得到index+1
url.length -1来控制你得到0
urls.length)来控制你得到一个可接受的值(在从异常中恢复后)当然,索引是私有的,但您仍然可以通过reflexion进行访问
urlList = new UrlList(...); // in test initialization
...
Field index = UrlList.class.getDeclaredField("index");
index.setAccessible(true);
index.setInt(urlList, i); // to set index
i = index.getInt(urlList); // to get indexhttps://stackoverflow.com/questions/24284629
复制相似问题