fintesse會把!{}標記的變量視爲HashTable對象,展現到頁面上的將是table格式(userguide中提到可以改變hashtable的css樣式)
====== java 代碼 =========
public Map getMap(Map map) {
Set set =map.keySet();
for(Object key:set){
System.out.println(key+":"+map.get(key));
}
return map;
}
====== fitnesse腳本 ============
!define teacher [!{name:laozhang,tech:Math}]
!define xiaoming [!{name:tom,age:18,teacher:${teacher}}]
|script|!-Test-! |
|$a= |getMap; |${xiaoming}|
==== 執行結果 =======
====== 分析原因 =================
1. 修改代碼
public Map getMap(Map map) {
Set set =map.keySet();
for(Object key:set){
System.out.println(key+":"+map.get(key).getClass().getName());
}
return map;
}
2. 執行fitnesse腳本後,查看日誌,發現teacher的value是String型,而不是hashtable對象
age:java.lang.String name:java.lang.String teacher:java.lang.String
3. 再次修改代碼
public Map getMap(Map map) {
Map output = new HashMap();
Set set = map.keySet();
for (Object key : set) {
System.out.println(key+":"+hashtableString2Map((String) map.get(key)));
output.put(key, hashtableString2Map((String) map.get(key)));
}
return output;
}
4. 執行fitnesse腳本後,查看輸出結果和日誌
age:18 name:tom teacher:{name=laozhang, tech=Math}
5. 再次分析原因,發現fitnesse會把map接口對象自動視爲hashtable(應該是爲了fitnesse展現出較好的樣式,但是如果把結果對象作爲參數傳入到其他方法內,可能會造成不可預期的錯誤,比如JSONObject的fromObject方法),爲了避免可能的錯誤,需要把輸出類型強制轉換爲HashMap,代碼如下
public HashMap getMap(Map map) {
Map output = new HashMap();
Set set = map.keySet();
for (Object key : set) {
System.out.println(key+":"+hashtableString2Map((String) map.get(key)));
output.put(key, hashtableString2Map((String) map.get(key)));
}
return (HashMap) output;
}
==== 新增方法hashtableString2Map ============
public static Object hashtableString2Map(String hashtableString) {
if (hashtableString.startsWith("<table class=\"hash_table\">")
&& hashtableString.endsWith("</table>")) {
Map map = new HashMap();
Document document = XMLParser
.getDocumentFromString(hashtableString);
Element parent = XMLParser.getRootNode(document);
List hash_rows = parent.elements();
String key = "";
String value = "";
for (int i = 0; i < hash_rows.size(); i++) {
Element hash_row = (Element) hash_rows.get(i);
List hashtableList = hash_row.elements();
for (int j = 0; j < hashtableList.size(); j++) {
Element ele = (Element) hashtableList.get(j);
String attrValue = ele.attributeValue("class");
if ("hash_key".equals(attrValue)) {
key = ele.getText();
} else if ("hash_value".equals(attrValue)) {
value = ele.getText();
}
map.put(key, value);
}
}
return map;
}
return hashtableString;
}
再次執行fitnesse腳本,得到結果