http://blog.csdn.net/doubeizhucele/article/details/42263887
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脚本,得到结果
原文:http://www.cnblogs.com/shengs/p/6582749.html