Why Do I Get an Invalidated-Handle Error?

This topic describes what you can do when Silk4J displays the following error message: The handle for this object has been invalidated.

This message indicates that something caused the object on which you called a method, for example click, to disappear. For example, if something causes the browser to navigate to a new page, during a method call in a web application, all objects on the previous page are automatically invalidated.

When testing a web application, the reason for this problem might be the built-in synchronization. For example, suppose that the application under test includes a shopping cart, and you have added an item to this shopping cart. You are waiting for the next page to be loaded and for the shopping cart to change its status to contains items. If the action, which adds the item, returns too soon, the shopping cart on the first page will be waiting for the status to change while the new page is loaded, causing the shopping cart of the first page to be invalidated. This behavior will result in an invalidated-handle error.

As a workaround, you should wait for an object that is only available on the second page before you verify the status of the shopping cart. As soon as the object is available, you can verify the status of the shopping cart, which is then correctly verified on the second page.

As a best practice for all applications, Micro Focus recommends creating a separate method for finding controls that you use often within tests. For example:
public Dialog getSaveAsDialog(Desktop desktop) {
 return desktop.find("//Dialog[@caption = 'Save As']");
The Find and FindAll methods return a handle for each matching object, which is only valid as long as the object in the application exists. For example, a handle to a dialog is invalid once the dialog is closed. Any attempts to execute methods on this handle after the dialog closes will throw an InvalidObjectHandleException. Similarly, handles for DOM objects on a Web page become invalid if the Web page is reloaded. Since it is a common practice to design test methods to be independent of each other and of order of execution, get new handles for the objects in each test method. In order not to duplicate the XPath query, helper methods, like getSaveAsDialog, can be created. For example:
public void testSaveAsDialog() {
 // ... some code to open the 'Save As' dialog (e.g by clicking a menu item) ...
 Dialog saveAsDialog = getSaveAsDialog(desktop);
 // ... some code to open the 'Save As' dialog again
 getSaveAsDialog(desktop).click(); // works as expected
 saveAsDialog.click(); //  fails because an InvalidObjectHandleException is thrown
The final line of code fails because it uses the object handle that no longer exists.