【发布时间】:2020-04-11 11:40:24
【问题描述】:
我最近从 C# 切换到 Java,但无法解决这个问题。我是使用 selenium 的自动化 UI。我喜欢为页面上的元素列表构建模型,检索属性,然后使用这些属性。在下面的示例中,我在 amazon.com 上搜索并获取结果列表。我有 SearchResultsModel 类,它代表返回的每个项目,public List<SearchResultModel> GetAllResults(bool title = false;bool isPrime = false;bool price = false) 方法从 UI 检索数据并将其放置在我的模型中,它具有允许我操作我想要检索的数据而不是检索所有内容的默认参数。然后我通过List<SearchResultModel> actual = myPage.GetAllResults(title:true,isPrime:true); 调用,在这种情况下,我得到一个SearchResultsModel 列表,每个列表只包含2 个属性——title 和isPrime。
在理想情况下,我应该从页面中检索所有数据,但这样做需要花费大量时间,并且违背了自动化比手动测试更快的整个目的。
我可以使用方法重载,但最终我会使用数十甚至数百个方法。在这个例子中,我只有 3 个属性,所以我最终会有 9 个方法,如果一个对象有 10 个属性,我什至不敢做数学。我可以使用 varagrs,但随后建立一个论点将变得一团糟。 我不确定如何在 Java 中解决这个问题。请指教
public class SearchResultsModel
{
//model that represents a single search result item
public string Title{get;set;}
public boolean IsPrime{get;set;}
public float Price {get;set;]
}
//method to retrieve all the search results from UI
public List<SearchResultModel> GetAllResults(bool title = false;bool isPrime = false;bool price = false)
{
List<SearchResultModel> toReturn = new List<SearchResultModel>();
IList<IWebElement> results = driver.FindElements(By.css("my locattors"))
foreach(IWebElement element in results)
{
SearchResultModel result = new SearchResultModel();
result.Title = title? element.FindElement(By.css("some locator")).GetText(): null;
result.IsPrime = isPrime? element.FindElement(By.css("some locator")).Selected(): false;
result.Price = price? element.FindElement(By.css("some locator")).GetText(): null;
toReturn.Add(result);
}
return toReturn;
}
//this is how I can invoke objects only with a specific properties
List<SearchResultModel> actual = myPage.GetAllResults(title:true,isPrime:true);
foreach(SearchResultModel model in actual)
{
Assert.That(model.isPrime == true);
}
【问题讨论】: