Following Hyperlinks
Problem
You want to obtain hyperlinks, simulate clicking on them, and test that the correct response is returned.
Solution
Use the WebResponse.getLinkWith( )
method to obtain a
WebLink
object, then call
WebLink.getRequest( )
to get a new
WebRequest
that you can execute. Executing this
second request simulates the user clicking on the link.
Discussion
The HTTP protocol is a series of requests and responses. Following a hyperlink is merely a case of issuing an HTTP GET request and checking the response. As you are adding new links to your web application, you should attempt to write a test first. The first time you run the test, it fails because the link does not exist. Here is a test that obtains a hyperlink and then attempts to follow it:
public void testFollowLinkToSubscriptionPage( ) throws Exception { // get the home page WebConversation webConversation = new WebConversation( ); WebResponse response = webConversation.getResponse( "http://localhost:8080/news"); WebLink subscriptionLink = response.getLinkWith("subscription"); // get a request to simulate clicking on the link WebRequest clickRequest = subscriptionLink.getRequest( ); // throws HttpNotFoundException if the link is broken WebResponse subscriptionPage = webConversation.getResponse(clickRequest); }
The WebResponse.getLinkWith( )
method searches for
the first hyperlink in the web page that contains some piece of text.
In our example, we are searching for a link like this:
<a href="someUrl">subscription</a> ...
Get Java Extreme Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.