How to get text from a FormText object (SWT)

Last edited on

Some classes, such as FormText ( org.eclipse.ui.forms.widgets.FormText ), may not provide a direct way to retrieve the text that they are displaying.

For verifying what such classes are displaying, one solution is to use screenshot verification points .

In some cases however, it is possible to rely on a class' private implementation details. (Of course, such private details may vary across Java versions, so are not ideal.) In the case of the FormText class, there is a private member called model which itself has a member variable called accessibletext, and this contains the displayed text.

However, because the model member is a private member, Squish cannot access it directly. Fortunately, this can be worked around by using Java's reflection API.

Here is an example that demonstrates how to do it:

def main():
    startApplication("MyApp.class")

    # Get reference to the FormText instance that we are interested in:
    formText = waitForObject({"isvisible": True, "type": "org.eclipse.ui.forms.widgets.FormText"})
    text = get_FormText_text(formText)
    test.log("Text: {}".format(text))
    snooze(1)

def get_FormText_text(formText):
    # Here is the claim that FormText has a private member "model":
    #  http://grepcode.com/file/repository.grepcode.com/java/eclipse.org/3.4.2/org.eclipse.ui/forms/3.3.103/org/eclipse/ui/forms/widgets/FormText.java/?v=source
    # So, we must retrieve this private member by using Java's
    # reflection API as described here:
    #  http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html
    field = formText.getClass().getDeclaredField("model")
    field.setAccessible(True)
    model = field.get(formText)
    # Inspecting this model object in the debugger it looks like it
    # already has a public member "accessibletext" that contains the
    # text being displayed, so we will return that:
    return model.accessibletext