就像我们在页面对象模式中所做的那样,将关键字方法维护为每个页面的单独类。
在调用关键字时,我们可以指定类名以及方法名。例如,LoginPage.login
例如,如果您在包下维护页面类,com.myproject.test.pages
您可以将调用的反射代码更改为,
public Object invokeKeywordMethod(String keywordName)
throws InvocationTargetException, IllegalAccessException, InstantiationException {
String[] keywords = keywordName.split("\\.");
if (keywords.length == 1)
throw new Error("Invalid keyword: " + keywordName + ". The keyword must be as ClassName.methodName");
String className = keywords[0];
String methodName = keywords[1];
Class<?> pageClass = getPageClass(className);
Method method;
try {
method = getPageClass("").getDeclaredMethod(methodName);
} catch (NoSuchMethodException e) {
throw new Error("The keyword method '" + methodName + "' is not found in the class");
}
return method.invoke(pageClass.newInstance());
}
private Class<?> getPageClass(String className) {
Class<?> pageClass = null;
try {
pageClass = Class.forName("com.myproject.test.pages." + className);
} catch (ClassNotFoundException e) {
throw new Error(className + " not found in package 'com.myproject.test.pages' ");
}
return pageClass;
}