如何优化Xamarin.UITest中GetQuery与GetWebQuery的重复条件逻辑?
统一Xamarin.UITest原生与Web查询的实现思路
针对你遇到的AppQuery和AppWebQuery类型不匹配、重复判断代码过多的问题,这里提供几个可行的整合思路:
思路1:利用基类QueryBase统一返回类型
AppQuery和AppWebQuery都继承自QueryBase抽象类,直接将查询方法的返回类型改为Func<AppQuery, QueryBase?>,就能统一兼容原生控件查询和Web元素的XPath查询,操作方法无需再做条件判断。
示例代码:
// 统一的查询方法 public Func<AppQuery, QueryBase?> GetUnifiedQuery() { if (IsWebElement) { // 返回Web元素XPath查询逻辑 return appQuery => appQuery.XPath("//div[@id='web-element']"); } else { // 返回原生控件查询逻辑 return appQuery => appQuery.Marked("native-button"); } } // 操作方法直接调用,无需判断 public void TapElement() { var query = GetUnifiedQuery(); App.Tap(query); }
UITest的Tap、EnterText等核心方法都支持接收返回QueryBase的委托,这种方式可以无缝兼容两种查询类型。
思路2:封装统一查询包装类
创建专门的包装类,把原生/Web查询的判断逻辑集中封装,对外提供统一的执行入口,后续修改查询规则只需改动包装类,所有操作方法无需调整。
示例代码:
public class UnifiedElementQuery { private readonly bool _isWebElement; private readonly string _nativeMarker; private readonly string _webXPath; public UnifiedElementQuery(bool isWebElement, string nativeMarker, string webXPath) { _isWebElement = isWebElement; _nativeMarker = nativeMarker; _webXPath = webXPath; } public QueryBase Execute(AppQuery appQuery) { return _isWebElement ? appQuery.XPath(_webXPath) : appQuery.Marked(_nativeMarker); } } // 获取查询实例 public UnifiedElementQuery GetElementQuery() { return new UnifiedElementQuery(IsWebElement, "native-button", "//div[@id='web-element']"); } // 操作方法中调用 public void TapElement() { var query = GetElementQuery(); App.Tap(q => query.Execute(q)); }
思路3:委托适配扩展
通过扩展方法明确处理AppWebQuery到QueryBase的类型转换,让代码逻辑更清晰,本质上和思路1一致,但可读性更强。
示例代码:
// 扩展方法:将AppWebQuery转换为QueryBase public static QueryBase AsQueryBase(this AppWebQuery webQuery) { return webQuery; } // 统一查询方法 public Func<AppQuery, QueryBase?> GetUnifiedQuery() { if (IsWebElement) { return appQuery => appQuery.XPath("//div[@id='web-element']").AsQueryBase(); } else { return appQuery => appQuery.Marked("native-button"); } }
内容的提问来源于stack exchange,提问作者Moshe Moadeb
相关产品推荐
相关产品推荐

