Java Reference
In-Depth Information
changed. By addressing the form by index, you're explicitly testing the form order on
the page. Address an element only through a list index if you want to test the order of
an element in that list.
To make the code resistant to list-order change, replace
HtmlForm form = page.getForms().get(0);
with
HtmlForm form = page.getFormByName("f");
Well, you might say, now you have a dependency on the form name “f” instead of on
form position 0. The benefit is that when you change the form order on a page, the
form name doesn't have to change, but the form index must change.
Lists are useful when the order of its elements matter. You may want to assert that
an anchor list is alphabetical or that a product list is in ascending price order.
12.3.8
Accessing elements with references
As you just saw, HtmlPage allows you to get specific elements by name. HtmlPage also
lets you get to any element by name,
ID
, or access key with any of the methods starting
with
getElementBy
such as
getElementById
,
getElementsByName
, and others
.
These
methods allow you to ask generic questions about the
HTML
model. For example,
when we wrote
HtmlForm form = page.getFormByName("f");
we ask specifically for a form named “f”. We can also write
HtmlForm form = (HtmlForm) page.getElementsByName("f").get(0);
which asks for all elements named “f” and then asks for the first element of that list.
Note two changes in the code: First, we cast the result to the desired type unless we
can work with an
HtmlElement
. Second, because element names aren't unique in a
page,
getElementsByName
returns a list of
HtmlElement
, which is why we have the call
to
get
.
If you can address the desired element by
ID
, you can use
getElementById
and do
away with the
get
call.
Calling
get
introduces some brittleness to this test because we're introducing a
dependency on the list order. If we wanted a more resilient test, and the element
didn't contain an
ID
, we'd need to resort to one of the following:
■
Traverse the list until we find the right element.
■
Use
getChildren
or
getChildNodes
to navigate down to the desired element.
Neither option is appealing, so the lesson here is to use
HTML
ID
s if you can. This will
allow you to create tests that are more resistant to change.
In general, for each
HTML
{Element}, there's a class called
Html{Element}
, for
example,
HtmlForm
. Some class names are more explicit than their
HTML
element