How can I simplify these method expression parameters?

In any case, I can change this method so as not to need an object, but just pass the parameter expression:

protected void FillInTextFor<T>(T obj, Expression<Func<T, object>> property) { var memberExpression = (MemberExpression)property.Body; var propertyInfo = (PropertyInfo)memberExpression.Member; // read value with reflection var value = (string)propertyInfo.GetValue(obj, null); // use the name and value of the property FillInText(propertyInfo.Name, value); } protected void FillInText(String elementId, String text) { VerifyElementPresent(elementId); Driver.FindElement(By.Id(elementId)).Clear(); Driver.FindElement(By.Id(elementId)).SendKeys(text); } 

Called as
var personToCreate = new PersonBuilder().RandomFirstName().Build(); FillInTextFor(personToCreate, a => a.FirstName);

I would just say FillInTextFor(_ => personToCreate.FirstName); or something similar

We are trying to make helper methods for Selenium tests. I want to pass an object and select a property, and it will automatically use the property name as the identifier of the element, and the text as the value for the string.

+4
source share
1 answer

You can create an overload as follows:

 protected void FillInTextFor<T>(Expression<Func<T>> property) { var memberExpression = (MemberExpression)property.Body; var propertyInfo = (PropertyInfo)memberExpression.Member; var compiled = property.Compile(); var value = compiled(); FillInText(propertyInfo.Name, value as string); } 

And name it using:

 var personToCreate = new PersonBuilder().RandomFirstName().Build(); FillInTextFor(() => personToCreate.FirstName); 
+3
source

Source: https://habr.com/ru/post/1468961/


All Articles