3
我想爲一個Java方法編寫一些JUnit測試,它接受一個基本的URL和目標URL,並返回相對於給定的基本URL的目標URL。JUnit測試這個特定的方法
我正在使用基於分類的分區來做我的測試集。目前我正在測試檢查以下內容:
- 檢查兩個輸入的URL是否有 相同的協議和主機;
- 檢查 路徑不一致時 相對URL調整 正確;
- 檢查基址爲 的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();
}
}
有些事情要試用..現在你知道如何去做。嘗試使用TDD再次寫入方法並重新編寫方法 - 這樣您就不會有未被單元測試覆蓋的代碼了。此外,您可能會提出一個更好的設計,因爲這是爲了第二次)。 – Gishu 2011-02-14 02:35:21
我覺得你的編輯出了問題;)。 – fwielstra 2011-02-14 11:31:11