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():

    # 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))

def get_FormText_text(formText):
    # Here is the claim that FormText has a private member "model":
    # So, we must retrieve this private member by using Java's
    # reflection API as described here:
    field = formText.getClass().getDeclaredField("model")
    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