I'm attempting to write a proxy for RemoteWebDriver to add custom logging for methods such as findElement etc. As an experiment I found a TimingHandler that just provides a start/stop time stamp for methods - it works fine outside of selenium. However, I can't get it to work with RemoteWebDriver.
Questions: Is there something about RemoteWebDriver which prevents the use of a proxy? Am I implementing this incorrectly? Is there a different/better way to do this?
public class TimingDynamicInvocationHandler implements InvocationHandler {
private static final Logger logger = LogManager.getLogger(TimingDynamicInvocationHandler.class.getName());
private final Map<String, Method> methods = new HashMap<>();
private Object target;
public TimingDynamicInvocationHandler(Object target) {
this.target = target;
for(Method method: target.getClass().getDeclaredMethods()) {
System.out.println("TDIHandler method: " + method.getName());
this.methods.put(method.getName(), method);
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("invoke method: " + method.getName());
long start = System.nanoTime();
Object result = methods.get(method.getName()).invoke(target, args);
long elapsed = System.nanoTime() - start;
logger.info("Executing {} finished in {} ns", method.getName(),
elapsed);
return result;
}
}
I am using TestNG and I have a BaseTest class, all tests extend from this. I use a beforeMethod which creates the driver. Without the proxy I do the following and it works as expected:
driver = new RemoteWebDriver(new URL(HUB_URL), caps);
driver.get(APP_URL);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
However when I change to use the proxy it hangs:
RemoteWebDriver rrDriver = new RemoteWebDriver(new URL(HUB_URL), caps);
TimingDynamicInvocationHandler handler = new TimingDynamicInvocationHandler(rrDriver);
Class<?> proxyClass = Proxy.getProxyClass(WebDriver.class.getClassLoader(), WebDriver.class);
driver = (WebDriver) proxyClass.getConstructor(TimingDynamicInvocationHandler.class).newInstance(handler);
I get the following output:
12:06:06.941 [main] ERROR BaseTest 175 beforeMethod - java.lang.NoSuchMethodException: com.sun.proxy.$Proxy22.<init>(com.timr.utils.aop.TimingDynamicInvocationHandler)