Chapter 17. PHPUnit and Selenium

Selenium RC is a test tool that allows you to write automated user-interface tests for web applications in any programming language against any HTTP website using any mainstream browser. It uses Selenium Core, a library that performs automated browser tasks using JavaScript. Selenium tests run directly in a browser, just as real users do. These tests can be used for both acceptance testing (by performing higher-level tests on the integrated system instead of just testing each unit of the system independently) and browser compatibility testing (by testing the web application on different operating systems and browsers).

The PHPUnit_Extensions_SeleniumTestCase test case extension implements the protocol to talk to Selenium RC as well as specialized assertion methods for web testing.

Example 17.1 shows how to test the contents of the <title> element of the http://www.example.com/ website.

Example 17.1: Usage example for PHPUnit_Extensions_SeleniumTestCase

<?php
require_once 'PHPUnit/Extensions/SeleniumTestCase.php';
 
class WebTest extends PHPUnit_Extensions_SeleniumTestCase
{
    protected function setUp()
    {
        $this->setBrowser('*firefox');
        $this->setBrowserUrl('http://www.example.com/');
    }
 
    public function testTitle()
    {
        $this->open('http://www.example.com/');
        $this->assertTitleEquals('Example Web Page');
    }
}
?>


Unlike with the PHPUnit_Framework_TestCase class, test case classes that extend PHPUnit_Extensions_SeleniumTestCase have to provide a setUp() method. This method is used to configure the Selenium RC session. See Table 17.1 for the list of methods that are available for this.

Table 17.1. Selenium RC API: Setup

MethodMeaning
void setBrowser(string $browser)Set the browser to be used by the Selenium RC server.
void setBrowserUrl(string $browserUrl)Set the base URL for the tests.
void setHost(string $host)Set the hostname for the connection to the Selenium RC server.
void setPort(int $port)Set the port for the connection to the Selenium RC server.
void setTimeout(int $timeout)Set the timeout for the connection to the Selenium RC server.


Table 17.2 lists the various methods that are available to simulate user actions inside the browser that is controlled by Selenium RC. After each action, the template method defaultAssertions($action) is called. The $action argument contains the name of the action that was performed.

Table 17.2. Selenium RC API: Actions

MethodMeaning
string start()Run the browser and set session id.
string stop()Close the browser and set session to NULL.
string open(string $url)Open the URL.
string close()Simulates the user clicking the "close" button in the titlebar of a popup window or tab.
string goBack()Simulates clicking on the browser's "go back" button.
string refresh()Simulates clicking on the browser's "refresh" button.
string click(string $locator)Clicks on a link, button, checkbox or radio button. If the click action causes a new page to load, call waitForPageToLoad().
string clickAndWait(string $locator)Clicks on a link, button, checkbox or radio button. Calls waitForPageToLoad().
string fireEvent(string $locator, string $eventName)Simulate an event to trigger the corresponding "onEvent" handler.
string keyDown(string $locator, string $keycode)Simulates a user pressing and holding a key.
string keyPress(string $locator, string $keycode)Simulates a user pressing and releasing a key.
string keyUp(string $locator, string $keycode)Simulates a user releasing a key.
string mouseDown(string $locator)Simulates a user pressing and holding the mouse button on the specified element.
string mouseOver(string $locator)Simulates a user hovering a mouse over the specified element.
string check(string $locator)Check a toggle-button (checkbox/radio).
string uncheck(string $locator)Uncheck a toggle-button (checkbox/radio).
string addSelection(string $locator, string $optionLocator)Add a selection to the set of selected options in a multi-select element using an option locator.
string removeSelection(string $locator, string $optionLocator)Remove a selection to the set of selected options in a multi-select element using an option locator.
string select(string $selectLocator, string $optionLocator)Select an option from a drop-down using an option locator.
string submit(string $locator)Submit the specified form.
string type(string $locator, string $value)Type into an input field.
string selectWindow(string $windowId)Selects a popup window; once a popup window has been selected, all commands go to that window. To select the main window again, use "null" as the target.
string setContext(string $context, string $logLevelThreshold)Writes a message to the status bar and adds a note to the browser-side log.
string answerOnNextPrompt(string $answer)Instructs Selenium to return the specified answer string in response to the next JavaScript prompt (window.prompt()).
string chooseCancelOnNextConfirmation()By default, Selenium's overridden window.confirm() function will return TRUE, as if the user had manually clicked OK. After running this command, the next call to confirm() will return FALSE, as if the user had clicked Cancel.
string waitForCondition(string $script[, int $timeout])Runs the specified JavaScript snippet repeatedly until it evaluates to TRUE.
string waitForPageToLoad([int $timeout])Waits for a new page to load.
string waitForPopUp(string $windowId[, int $timeout])Wait for a popup window to appear and load up.


Table 17.3 lists the various methods that are available to query the browser that is controlled by Selenium RC for data.

Table 17.3. Selenium RC API: Queries

MethodMeaning
string getAlert()Retrieves the message of a JavaScript alert generated during the previous action.
array getAllButtons()Returns the IDs of all buttons on the page.
array getAllFields()Returns the IDs of all input fields on the page.
array getAllLinks()Returns the IDs of all links on the page.
string getBodyText()Returns the entire text of the page.
string getConfirmation()Returns the message of a JavaScript confirmation dialog generated during the previous action.
int getCursorPosition(string $locator)Returns the text cursor position in the given input element or textarea.
void setCursorPosition(string $locator, int $position)Moves the text cursor to the specified position in the given input element or textarea.
string getElementAttribute(string $attributeLocator)Returns the value of an element attribute.
string getEval(string $script)Returns the result of evaluating the specified JavaScript snippet.
string getExpression(string $expression)Returns the specified expression.
string getHtmlSource()Returns the entire HTML source between the opening and closing "html" tags.
string getLocation()Returns the absolute URL of the current page.
string getPrompt()Returns the message of a JavaScript question prompt dialog generated during the previous action.
string getSelectedId(string $selectLocator)Returns option element ID for selected option in the specified select element.
array getSelectedIds(string $selectLocator)Returns all option element IDs for selected options in the specified select or multi-select element.
string getSelectedIndex(string $selectLocator)Returns option index (option number, starting at 0) for selected option in the specified select element.
array getSelectedIndexes(string $selectLocator)Returns all option indexes (option number, starting at 0) for selected options in the specified select or multi-select element.
string getSelectedLabel(string $selectLocator)Returns all option labels (visible text) for selected options in the specified select element.
array getSelectedLabels(string $selectLocator)Returns all option labels (visible text) for selected options in the specified select or multi-select element.
string getSelectedValue(string $selectLocator)Returns option value (value attribute) for selected option in the specified select element.
array getSelectedValues(string $selectLocator)Returns all option values (value attributes) for selected options in the specified select or multi-select element.
array getSelectOptions(string $selectLocator)Returns all option labels in the specified select drop-down.
string getTable(string $tableCellAddress)Returns the text from a cell of a table.
string getText(string $locator)Returns the text of an element.
string getTitle()Returns the title of the current page.
string getValue(string $locator) Returns the (whitespace-trimmed) value of an input field (or anything else with a value parameter).
boolean isAlertPresent()Determines whether an alert occured.
boolean isChecked($locator)Determines whether a toggle-button (checkbox/radio) is checked.
boolean isConfirmationPresent()Determines whether confirm() has been called.
boolean isEditable($locator)Determines whether the specified input element is editable.
boolean isElementPresent($locator)Determines whether the specified element is somewhere on the page.
boolean isPromptPresent()Determines whether a prompt is present.
boolean isSomethingSelected(string $selectLocator)Determines whether some option in a drop-down menu is selected.
boolean isTextPresent(string $pattern)Determines whether the specified text pattern appears somewhere on the rendered page shown to the user.
boolean isVisible($locator)Determines if the specified element is visible.


Many of the Selenium commands operate on $locator arguments. Their syntax is described in the Selenium Core Reference.

Table 17.4 lists the various assertion methods that PHPUnit_Extensions_SeleniumTestCase provides.

Table 17.4. Assertions

AssertionMeaning
void assertAlertPresent()Reports an error if no alert is present.
void assertNoAlertPresent()Reports an error if an alert is present.
void assertChecked(string $locator)Reports an error if the element identified by $locator is not checked.
void assertNotChecked(string $locator)Reports an error if the element identified by $locator is checked.
void assertConfirmationPresent()Reports an error if no confirmation is present.
void assertNoConfirmationPresent()Reports an error if a confirmation is present.
void assertEditable(string $locator)Reports an error if the element identified by $locator is not editable.
void assertNotEditable(string $locator)Reports an error if the element identified by $locator is editable.
void assertElementValueEquals(string $locator, string $text)Reports an error if the value of the element identified by $locator is not equal to the given $text.
void assertElementValueNotEquals(string $locator, string $text)Reports an error if the value of the element identified by $locator is equal to the given $text.
void assertElementContainsText(string $locator, string $text)Reports an error if the element identified by $locator does not contain the given $text.
void assertElementNotContainsText(string $locator, string $text)Reports an error if the element identified by $locator contains the given $text.
void assertElementPresent(string $locator)Reports an error if the element identified by $locator is not present.
void assertElementNotPresent(string $locator)Reports an error if the element identified by $locator is present.
void assertLocationEquals(string $location)Reports an error if the current location is not equal to the given $location.
void assertLocationNotEquals(string $location)Reports an error if the current location is equal to the given $location.
void assertPromptPresent()Reports an error if no prompt is present.
void assertNoPromptPresent()Reports an error if a prompt is present.
void assertSomethingSelected(string $selectLocator)Reports an error if the option identified by $selectLocator is not selected.
void assertNothingSelected(string $selectLocator)Reports an error if the option identified by $selectLocator is selected.
void assertTextPresent(string $pattern)Reports an error if the given $pattern is not present.
void assertTextNotPresent(string $pattern)Reports an error if the given $pattern is present.
void assertTitleEquals(string $title)Reports an error if the current title is not equal to the given $title.
void assertTitleNotEquals(string $title)Reports an error if the current title is equal to the given $title.
void assertVisible(string $locator)Reports an error if the element identified by $locator is not visible.
void assertNotVisible(string $locator)Reports an error if the element identified by $locator is visible.