我正在尝试为Java方法编写一些JUnit测试,该方法采用基本URL和目标URL,并返回相对于给定基本URL的目标URL。
我正在使用基于类别的分区来制作我的测试集。目前我正在测试检查以下内容:
我想知道其他人如何使用JUnit测试这个方法?我错过了任何标准吗?
/**
* This method converts an absolute url to an url relative to a given base-url.
* The algorithm is somewhat chaotic, but it works (Maybe rewrite it).
* Be careful, the method is ".mm"-specific. Something like this should be included
* in the librarys, but I couldn't find it. You can create a new absolute url with
* "new URL(URL context, URL relative)".
*/
public static String toRelativeURL(URL base, URL target) {
// Precondition: If URL is a path to folder, then it must end with '/' character.
if( (base.getProtocol().equals(target.getProtocol())) &&
(base.getHost().equals(target.getHost()))) {
String baseString = base.getFile();
String targetString = target.getFile();
String result = "";
//remove filename from URL
baseString = baseString.substring(0, baseString.lastIndexOf("/")+1);
//remove filename from URL
targetString = targetString.substring(0, targetString.lastIndexOf("/")+1);
StringTokenizer baseTokens = new StringTokenizer(baseString,"/");//Maybe this causes problems under windows
StringTokenizer targetTokens = new StringTokenizer(targetString,"/");//Maybe this causes problems under windows
String nextBaseToken = "", nextTargetToken = "";
//Algorithm
while(baseTokens.hasMoreTokens() && targetTokens.hasMoreTokens()) {
nextBaseToken = baseTokens.nextToken();
nextTargetToken = targetTokens.nextToken();
System.out.println("while1");
if (!(nextBaseToken.equals(nextTargetToken))) {
System.out.println("if1");
while(true) {
result = result.concat("../");
System.out.println(result);
if (!baseTokens.hasMoreTokens()) {
System.out.println("break1");
break;
}
System.out.println("break2");
nextBaseToken = baseTokens.nextToken();
}
while(true) {
result = result.concat(nextTargetToken+"/");
System.out.println(result);
if (!targetTokens.hasMoreTokens()) {
System.out.println("break3");
break;
}
System.out.println("break4");
nextTargetToken = targetTokens.nextToken();
}
String temp = target.getFile();
result = result.concat(temp.substring(temp.lastIndexOf("/")+1,temp.length()));
System.out.println("1");
return result;
}
}
while(baseTokens.hasMoreTokens()) {
result = result.concat("../");
baseTokens.nextToken();
}
while(targetTokens.hasMoreTokens()) {
nextTargetToken = targetTokens.nextToken();
result = result.concat(nextTargetToken + "/");
}
String temp = target.getFile();
result = result.concat(temp.substring(temp.lastIndexOf("/")+1,temp.length()));
System.out.println("2");
return result;
}
System.out.println("3");
return target.toString();
}
}
答案 0 :(得分:1)
只是一些想法......
http://host/app/bla?param1=value¶m2=value
),生成的相对网址是否包含参数?http://host
,则会导致IndexOutOfBoundException
上的targetString.lastIndexOf("/")
...同样适用于基本网址。