diff --git a/website_and_docs/content/documentation/test_practices/encouraged/page_object_models.en.md b/website_and_docs/content/documentation/test_practices/encouraged/page_object_models.en.md index 995dfbcc064e..648d76f3d4be 100644 --- a/website_and_docs/content/documentation/test_practices/encouraged/page_object_models.en.md +++ b/website_and_docs/content/documentation/test_practices/encouraged/page_object_models.en.md @@ -202,7 +202,152 @@ page itself. The same principles used for page objects can be used to create "Page _Component_ Objects" that represent discrete chunks of the page and can be included in page objects. These component objects can provide references to the elements inside those discrete chunks, and -methods to leverage the functionality provided by them. You can even +methods to leverage the functionality provided by them. + +For example, a Product page has multiple products. + +```html + +
+ Products +
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+
+``` + +Each product is a component of the Products page. + + +```html + +
+
Backpack
+
+
$29.99
+ +
+
+``` + +The Product page HAS-A list of products. This relationship is called Composition. In simpler terms, something is _composed of_ another thing. + +```java +public abstract class BasePage { + protected WebDriver driver; + + public BasePage(WebDriver driver) { + this.driver = driver; + } +} + +// Page Object +public class ProductsPage extends BasePage { + public ProductsPage(WebDriver driver) { + super(driver); + // No assertions, throws an exception if the element is not loaded + new WebDriverWait(driver, Duration.ofSeconds(3)) + .until(d -> d.findElement(By.className​("header_container"))); + } + + // Returning a list of products is a service of the page + public List getProducts() { + return driver.findElements(By.className​("inventory_item")) + .stream() + .map(e -> new Product(e)) // Map WebElement to a product component + .toList(); + } + + // Return a specific product using a boolean-valued function (predicate) + // This is the behavioral Strategy Pattern from GoF + public Product getProduct(Predicate condition) { + return getProducts() + .stream() + .filter(condition) // Filter by product name or price + .findFirst() + .orElseThrow(); + } +} +``` + +The Product component object is used inside the Products page object. + +```java +public abstract class BaseComponent { + protected WebElement root; + + public BaseComponent(WebElement root) { + this.root = root; + } +} + +// Page Component Object +public class Product extends BaseComponent { + // The root element contains the entire component + public Product(WebElement root) { + super(root); // inventory_item + } + + public String getName() { + // Locating an element begins at the root of the component + return root.findElement(By.className("inventory_item_name")).getText(); + } + + public BigDecimal getPrice() { + return new BigDecimal( + root.findElement(By.className("inventory_item_price")) + .getText() + .replace("$", "") + ).setScale(2, RoundingMode.UNNECESSARY); // Sanitation and formatting + } + + public void addToCart() { + root.findElement(By.id("add-to-cart-backpack")).click(); + } +} +``` + +So now, the products test would use the page object and the page component object as follows. + +```java +public class ProductsTest { + @Test + public void testProductInventory() { + var productsPage = new ProductsPage(driver); + var products = productsPage.getProducts(); + assertEquals(6, products.size()); // expected, actual + } + + @Test + public void testProductPrices() { + var productsPage = new ProductsPage(driver); + + // Pass a lambda expression (predicate) to filter the list of products + // The predicate or "strategy" is the behavior passed as parameter + var backpack = productsPage.getProduct(p -> p.getName().equals("Backpack")); + var bikeLight = productsPage.getProduct(p -> p.getName().equals("Bike Light")); + + assertEquals(new BigDecimal("29.99"), backpack.getPrice()); + assertEquals(new BigDecimal("9.99"), bikeLight.getPrice()); + } +} +``` + +The page and component are represented by their own objects. Both objects only have methods for the **services** they offer, which matches the real-world application in object-oriented programming. + +You can even nest component objects inside other component objects for more complex pages. If a page in the AUT has multiple components, or common components used throughout the site (e.g. a navigation bar), then it diff --git a/website_and_docs/content/documentation/test_practices/encouraged/page_object_models.ja.md b/website_and_docs/content/documentation/test_practices/encouraged/page_object_models.ja.md index 6444f070e884..a269bd4183ce 100644 --- a/website_and_docs/content/documentation/test_practices/encouraged/page_object_models.ja.md +++ b/website_and_docs/content/documentation/test_practices/encouraged/page_object_models.ja.md @@ -9,24 +9,43 @@ aliases: [ ] --- -ページオブジェクトは、テストメンテナンスを強化し、コードの重複を減らすためのテスト自動化で一般的になったデザインパターンです。 -ページオブジェクトは、AUT(テスト対象アプリケーション)のページへのインターフェイスとして機能するオブジェクト指向クラスです。 -テストは、そのページのUIと対話する必要があるときは常に、このページオブジェクトクラスのメソッドを使用します。 -利点は、ページのUIが変更された場合、テスト自体を変更する必要はなく、ページオブジェクト内のコードのみを変更する必要があることです。 -その後、その新しいUIをサポートするためのすべての変更は1か所に配置されます。 - -ページオブジェクトデザインパターンには、次の利点があります。 - -* テストコードと、ロケーター(またはUIマップを使用している場合はロケーター)、レイアウトなどのページ固有のコードを明確に分離します。 -* これらのサービスをテスト全体に分散させるのではなく、ページによって提供されるサービスまたは操作用の単一のリポジトリがあります。 - -どちらの場合でも、これにより、UIの変更により必要な変更をすべて1か所で行うことができます。 -この'テストデザインパターン'が広く使用されるようになったため、この手法に関する有用な情報は多数のブログで見つけることができます。 -詳細を知りたい読者には、このテーマに関するブログをインターネットで検索することをお勧めします。 -多くの人がこの設計パターンについて書いており、このユーザーガイドの範囲を超えた有用なヒントを提供できます。 -ただし、簡単に始めるために、ページオブジェクトを簡単な例で説明します。 - -最初に、ページオブジェクトを使用しないテスト自動化の典型的な例を考えてみましょう。 +Note: this page has merged contents from multiple sources, including +the [Selenium wiki](https://github.com/SeleniumHQ/selenium/wiki/PageObjects) + +## Overview + +Within your web app's UI, there are areas where your tests interact with. +A Page Object only models these as objects within the test code. +This reduces the amount of duplicated code and means that if the UI changes, +the fix needs only to be applied in one place. + +Page Object is a Design Pattern that has become popular in test automation for +enhancing test maintenance and reducing code duplication. A page object is an +object-oriented class that serves as an interface to a page of your AUT. The +tests then use the methods of this page object class whenever they need to +interact with the UI of that page. The benefit is that if the UI changes for +the page, the tests themselves don’t need to change, only the code within the +page object needs to change. Subsequently, all changes to support that new UI +are located in one place. + +### Advantages + +* There is a clean separation between the test code and page-specific code, such as + locators (or their use if you’re using a UI Map) and layout. +* There is a single repository for the services or operations the page offers + rather than having these services scattered throughout the tests. + +In both cases, this allows any modifications required due to UI changes to all +be made in one place. Helpful information on this technique can be found on +numerous blogs as this ‘test design pattern’ is becoming widely used. We +encourage readers who wish to know more to search the internet for blogs +on this subject. Many have written on this design pattern and can provide +helpful tips beyond the scope of this user guide. To get you started, +we’ll illustrate page objects with a simple example. + +### Examples +First, consider an example, typical of test automation, that does not use a +page object: ```java /*** @@ -38,7 +57,7 @@ public class Login { // fill login data on sign-in page driver.findElement(By.name("user_name")).sendKeys("userName"); driver.findElement(By.name("password")).sendKeys("my supersecret password"); - driver.findElement(By.name("sign_in")).click(); + driver.findElement(By.name("sign-in")).click(); // verify h1 tag is "Hello userName" after login driver.findElement(By.tagName("h1")).isDisplayed(); @@ -47,14 +66,17 @@ public class Login { } ``` -このアプローチには2つの問題があります。 +There are two problems with this approach. -* テスト方法とAUTのロケーター(この例ではID)の間に区別はありません。 -どちらも単一のメソッドで絡み合っています。 -AUTのUIが識別子、レイアウト、またはログインの入力および処理方法を変更する場合、テスト自体を変更する必要があります。 -* IDロケーターは、このログインページを使用する必要があったすべてのテストで、複数のテストに分散されます。 +* There is no separation between the test method and the AUT’s locators (IDs in +this example); both are intertwined in a single method. If the AUT’s UI changes +its identifiers, layout, or how a login is input and processed, the test itself +must change. +* The ID-locators would be spread in multiple tests, in all tests that had to +use this login page. -ページオブジェクトの手法を適用すると、この例は、サインインページのページオブジェクトの次の例のように書き換えることができます。 +Applying the page object techniques, this example could be rewritten like this +in the following example of a page object for a Sign-in page. ```java import org.openqa.selenium.By; @@ -75,7 +97,7 @@ public class SignInPage { public SignInPage(WebDriver driver){ this.driver = driver; - if (!driver.getTitle().equals("Sign In Page")) { + if (!driver.getTitle().equals("Sign In Page")) { throw new IllegalStateException("This is not Sign In Page," + " current page is: " + driver.getCurrentUrl()); } @@ -97,7 +119,7 @@ public class SignInPage { } ``` -そして、ホームページのページオブジェクトは次のようになります。 +and page object for a Home page could look like this. ```java import org.openqa.selenium.By; @@ -139,7 +161,7 @@ public class HomePage { } ``` -したがって、ログインテストでは、これら2つのページオブジェクトを次のように使用します。 +So now, the login test would use these two page objects as follows. ```java /*** @@ -157,23 +179,322 @@ public class TestLogin { } ``` -ページオブジェクトの設計方法には多くの柔軟性がありますが、テストコードの望ましい保守性を得るための基本的なルールがいくつかあります。 +There is a lot of flexibility in how the page objects may be designed, but +there are a few basic rules for getting the desired maintainability of your +test code. + +## Assertions in Page Objects +Page objects themselves should never make verifications or assertions. This is +part of your test and should always be within the test’s code, never in an page +object. The page object will contain the representation of the page, and the +services the page provides via methods but no code related to what is being +tested should be within the page object. + +There is one, single, verification which can, and should, be within the page +object and that is to verify that the page, and possibly critical elements on +the page, were loaded correctly. This verification should be done while +instantiating the page object. In the examples above, both the SignInPage and +HomePage constructors check that the expected page is available and ready for +requests from the test. + +## Page Component Objects +A page object does not necessarily need to represent all the parts of a +page itself. The same principles used for page objects can be used to +create "Page _Component_ Objects" that represent discrete chunks of the +page and can be included in page objects. These component objects can +provide references to the elements inside those discrete chunks, and +methods to leverage the functionality provided by them. + +For example, a Product page has multiple products. + +```html + +
+ Products +
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+
+``` + +Each product is a component of the Products page. + + +```html + +
+
Backpack
+
+
$29.99
+ +
+
+``` + +The Product page HAS-A list of products. This relationship is called Composition. In simpler terms, something is _composed of_ another thing. + +```java +public abstract class BasePage { + protected WebDriver driver; + + public BasePage(WebDriver driver) { + this.driver = driver; + } +} + +// Page Object +public class ProductsPage extends BasePage { + public ProductsPage(WebDriver driver) { + super(driver); + // No assertions, throws an exception if the element is not loaded + new WebDriverWait(driver, Duration.ofSeconds(3)) + .until(d -> d.findElement(By.className​("header_container"))); + } + + // Returning a list of products is a service of the page + public List getProducts() { + return driver.findElements(By.className​("inventory_item")) + .stream() + .map(e -> new Product(e)) // Map WebElement to a product component + .toList(); + } + + // Return a specific product using a boolean-valued function (predicate) + // This is the behavioral Strategy Pattern from GoF + public Product getProduct(Predicate condition) { + return getProducts() + .stream() + .filter(condition) // Filter by product name or price + .findFirst() + .orElseThrow(); + } +} +``` + +The Product component object is used inside the Products page object. + +```java +public abstract class BaseComponent { + protected WebElement root; + + public BaseComponent(WebElement root) { + this.root = root; + } +} + +// Page Component Object +public class Product extends BaseComponent { + // The root element contains the entire component + public Product(WebElement root) { + super(root); // inventory_item + } + + public String getName() { + // Locating an element begins at the root of the component + return root.findElement(By.className("inventory_item_name")).getText(); + } + + public BigDecimal getPrice() { + return new BigDecimal( + root.findElement(By.className("inventory_item_price")) + .getText() + .replace("$", "") + ).setScale(2, RoundingMode.UNNECESSARY); // Sanitation and formatting + } + + public void addToCart() { + root.findElement(By.id("add-to-cart-backpack")).click(); + } +} +``` + +So now, the products test would use the page object and the page component object as follows. + +```java +public class ProductsTest { + @Test + public void testProductInventory() { + var productsPage = new ProductsPage(driver); + var products = productsPage.getProducts(); + assertEquals(6, products.size()); // expected, actual + } + + @Test + public void testProductPrices() { + var productsPage = new ProductsPage(driver); + + // Pass a lambda expression (predicate) to filter the list of products + // The predicate or "strategy" is the behavior passed as parameter + var backpack = productsPage.getProduct(p -> p.getName().equals("Backpack")); + var bikeLight = productsPage.getProduct(p -> p.getName().equals("Bike Light")); + + assertEquals(new BigDecimal("29.99"), backpack.getPrice()); + assertEquals(new BigDecimal("9.99"), bikeLight.getPrice()); + } +} +``` + +The page and component are represented by their own objects. Both objects only have methods for the **services** they offer, which matches the real-world application in object-oriented programming. + +You can even +nest component objects inside other component objects for more complex +pages. If a page in the AUT has multiple components, or common +components used throughout the site (e.g. a navigation bar), then it +may improve maintainability and reduce code duplication. + +## Other Design Patterns Used in Testing +There are other design patterns that also may be used in testing. Some use a +Page Factory for instantiating their page objects. Discussing all of these is +beyond the scope of this user guide. Here, we merely want to introduce the +concepts to make the reader aware of some of the things that can be done. As +was mentioned earlier, many have blogged on this topic and we encourage the +reader to search for blogs on these topics. + +## Implementation Notes + + +PageObjects can be thought of as facing in two directions simultaneously. Facing toward the developer of a test, they represent the **services** offered by a particular page. Facing away from the developer, they should be the only thing that has a deep knowledge of the structure of the HTML of a page (or part of a page) It's simplest to think of the methods on a Page Object as offering the "services" that a page offers rather than exposing the details and mechanics of the page. As an example, think of the inbox of any web-based email system. Amongst the services it offers are the ability to compose a new email, choose to read a single email, and list the subject lines of the emails in the inbox. How these are implemented shouldn't matter to the test. + +Because we're encouraging the developer of a test to try and think about the services they're interacting with rather than the implementation, PageObjects should seldom expose the underlying WebDriver instance. To facilitate this, methods on the PageObject should return other PageObjects. This means we can effectively model the user's journey through our application. It also means that should the way that pages relate to one another change (like when the login page asks the user to change their password the first time they log into a service when it previously didn't do that), simply changing the appropriate method's signature will cause the tests to fail to compile. Put another way; we can tell which tests would fail without needing to run them when we change the relationship between pages and reflect this in the PageObjects. + +One consequence of this approach is that it may be necessary to model (for example) both a successful and unsuccessful login; or a click could have a different result depending on the app's state. When this happens, it is common to have multiple methods on the PageObject: + +``` +public class LoginPage { + public HomePage loginAs(String username, String password) { + // ... clever magic happens here + } + + public LoginPage loginAsExpectingError(String username, String password) { + // ... failed login here, maybe because one or both of the username and password are wrong + } + + public String getErrorMessage() { + // So we can verify that the correct error is shown + } +} +``` + +The code presented above shows an important point: the tests, not the PageObjects, should be responsible for making assertions about the state of a page. For example: + +``` +public void testMessagesAreReadOrUnread() { + Inbox inbox = new Inbox(driver); + inbox.assertMessageWithSubjectIsUnread("I like cheese"); + inbox.assertMessageWithSubjectIsNotUnread("I'm not fond of tofu"); +} +``` + +could be re-written as: + +``` +public void testMessagesAreReadOrUnread() { + Inbox inbox = new Inbox(driver); + assertTrue(inbox.isMessageWithSubjectIsUnread("I like cheese")); + assertFalse(inbox.isMessageWithSubjectIsUnread("I'm not fond of tofu")); +} +``` + +Of course, as with every guideline, there are exceptions, and one that is commonly seen with PageObjects is to check that the WebDriver is on the correct page when we instantiate the PageObject. This is done in the example below. + +Finally, a PageObject need not represent an entire page. It may represent a section that appears frequently within a site or page, such as site navigation. The essential principle is that there is only one place in your test suite with knowledge of the structure of the HTML of a particular (part of a) page. + +## Summary -ページオブジェクト自体は、検証やアサーションを行うべきではありません。 -これはテストの一部であり、常にページオブジェクトではなく、テストのコード内にある必要があります。 -ページオブジェクトには、ページの表現と、ページがメソッドを介して提供するサービスが含まれますが、テスト対象に関連するコードはページオブジェクト内に存在しないようにします。 +* The public methods represent the services that the page offers +* Try not to expose the internals of the page +* Generally don't make assertions +* Methods return other PageObjects +* Need not represent an entire page +* Different results for the same action are modelled as different methods + +## Example + +``` +public class LoginPage { + private final WebDriver driver; + + public LoginPage(WebDriver driver) { + this.driver = driver; + + // Check that we're on the right page. + if (!"Login".equals(driver.getTitle())) { + // Alternatively, we could navigate to the login page, perhaps logging out first + throw new IllegalStateException("This is not the login page"); + } + } + + // The login page contains several HTML elements that will be represented as WebElements. + // The locators for these elements should only be defined once. + By usernameLocator = By.id("username"); + By passwordLocator = By.id("passwd"); + By loginButtonLocator = By.id("login"); + + // The login page allows the user to type their username into the username field + public LoginPage typeUsername(String username) { + // This is the only place that "knows" how to enter a username + driver.findElement(usernameLocator).sendKeys(username); + + // Return the current page object as this action doesn't navigate to a page represented by another PageObject + return this; + } + + // The login page allows the user to type their password into the password field + public LoginPage typePassword(String password) { + // This is the only place that "knows" how to enter a password + driver.findElement(passwordLocator).sendKeys(password); + + // Return the current page object as this action doesn't navigate to a page represented by another PageObject + return this; + } + + // The login page allows the user to submit the login form + public HomePage submitLogin() { + // This is the only place that submits the login form and expects the destination to be the home page. + // A seperate method should be created for the instance of clicking login whilst expecting a login failure. + driver.findElement(loginButtonLocator).submit(); + + // Return a new page object representing the destination. Should the login page ever + // go somewhere else (for example, a legal disclaimer) then changing the method signature + // for this method will mean that all tests that rely on this behaviour won't compile. + return new HomePage(driver); + } + + // The login page allows the user to submit the login form knowing that an invalid username and / or password were entered + public LoginPage submitLoginExpectingFailure() { + // This is the only place that submits the login form and expects the destination to be the login page due to login failure. + driver.findElement(loginButtonLocator).submit(); + + // Return a new page object representing the destination. Should the user ever be navigated to the home page after submiting a login with credentials + // expected to fail login, the script will fail when it attempts to instantiate the LoginPage PageObject. + return new LoginPage(driver); + } + + // Conceptually, the login page offers the user the service of being able to "log into" + // the application using a user name and password. + public HomePage loginAs(String username, String password) { + // The PageObject methods that enter username, password & submit login have already defined and should not be repeated here. + typeUsername(username); + typePassword(password); + return submitLogin(); + } +} + +``` -ページオブジェクト内に存在する可能性のある単一の検証があります。 -これは、ページおよびページ上の重要な要素が正しく読み込まれたことを検証するためのものです。 -この検証は、ページオブジェクトをインスタンス化する間に実行する必要があります。 -上記の例では、SignInPageコンストラクターとHomePageコンストラクターの両方が期待するページを取得し、テストからの要求に対応できることを確認します。 -ページオブジェクトは、必ずしもページ全体を表す必要はありません。 -ページオブジェクトデザインパターンは、ページ上のコンポーネントを表すために使用できます。 -AUTのページに複数のコンポーネントがある場合、コンポーネントごとに個別のページオブジェクトがあると、保守性が向上する場合があります。 +## Support in WebDriver -また、テストで使用できる他のデザインパターンがあります。 -ページファクトリを使用してページオブジェクトをインスタンス化するものもあります。 -これらすべてについて議論することは、このユーザーガイドの範囲を超えています。 -ここでは、読者にできることのいくつかを認識させるための概念を紹介したいだけです。 -前述のように、多くの人がこのトピックについてブログを書いていますし、読者がこれらのトピックに関するブログを検索することをお勧めします。 +There is a PageFactory in the support package that provides support for this pattern and helps to remove some boiler-plate code from your Page Objects at the same time. diff --git a/website_and_docs/content/documentation/test_practices/encouraged/page_object_models.pt-br.md b/website_and_docs/content/documentation/test_practices/encouraged/page_object_models.pt-br.md index 9999903f548e..ea0efaad9daf 100644 --- a/website_and_docs/content/documentation/test_practices/encouraged/page_object_models.pt-br.md +++ b/website_and_docs/content/documentation/test_practices/encouraged/page_object_models.pt-br.md @@ -9,32 +9,43 @@ aliases: [ ] --- -Objeto de página é um padrão de design que se tornou popular na automação de teste para -melhorar a manutenção de teste e reduzir a duplicação de código. Um objeto de página é uma -classe orientada a objetos que serve como uma interface para uma página de seu AUT. -Os testes então usam os métodos desta classe de objeto de página sempre que precisam -interagir com a interface do usuário dessa página. O benefício é que, se a IU mudar para -a página, os próprios testes não precisam ser alterados, apenas o código dentro do -o objeto da página precisa ser alterado. Posteriormente, todas as alterações para oferecer suporte a essa nova IU -estão localizados em um só lugar. - -O padrão de design do objeto de página oferece as seguintes vantagens: - -* Há uma separação clara entre o código de teste e o código específico da página, como - localizadores (ou seu uso se você estiver usando um mapa de interface do usuário) e layout. -* Existe um único repositório para os serviços ou operações oferecidos pela página - em vez de ter esses serviços espalhados pelos testes. - -Em ambos os casos, isso permite qualquer modificação necessária devido a mudanças na IU -ser feito em um só lugar. Informações úteis sobre esta técnica podem ser encontradas em -vários blogs, já que esse ‘padrão de design de teste’ está se tornando amplamente usado. Nós -incentivamos o leitor que deseja saber mais a pesquisar blogs na internet -nesse assunto. Muitos escreveram sobre este padrão de design e podem fornecer -dicas úteis que vão além do escopo deste guia do usuário. Para começar, no entanto, -vamos ilustrar objetos de página com um exemplo simples. - -Primeiro, considere um exemplo, típico de automação de teste, que não usa um -objeto de página: +Note: this page has merged contents from multiple sources, including +the [Selenium wiki](https://github.com/SeleniumHQ/selenium/wiki/PageObjects) + +## Overview + +Within your web app's UI, there are areas where your tests interact with. +A Page Object only models these as objects within the test code. +This reduces the amount of duplicated code and means that if the UI changes, +the fix needs only to be applied in one place. + +Page Object is a Design Pattern that has become popular in test automation for +enhancing test maintenance and reducing code duplication. A page object is an +object-oriented class that serves as an interface to a page of your AUT. The +tests then use the methods of this page object class whenever they need to +interact with the UI of that page. The benefit is that if the UI changes for +the page, the tests themselves don’t need to change, only the code within the +page object needs to change. Subsequently, all changes to support that new UI +are located in one place. + +### Advantages + +* There is a clean separation between the test code and page-specific code, such as + locators (or their use if you’re using a UI Map) and layout. +* There is a single repository for the services or operations the page offers + rather than having these services scattered throughout the tests. + +In both cases, this allows any modifications required due to UI changes to all +be made in one place. Helpful information on this technique can be found on +numerous blogs as this ‘test design pattern’ is becoming widely used. We +encourage readers who wish to know more to search the internet for blogs +on this subject. Many have written on this design pattern and can provide +helpful tips beyond the scope of this user guide. To get you started, +we’ll illustrate page objects with a simple example. + +### Examples +First, consider an example, typical of test automation, that does not use a +page object: ```java /*** @@ -43,36 +54,36 @@ objeto de página: public class Login { public void testLogin() { - // preenche dados de login na página de entrada + // fill login data on sign-in page driver.findElement(By.name("user_name")).sendKeys("userName"); driver.findElement(By.name("password")).sendKeys("my supersecret password"); driver.findElement(By.name("sign-in")).click(); - // verifica que a tag h1 é "Hello userName" após o login + // verify h1 tag is "Hello userName" after login driver.findElement(By.tagName("h1")).isDisplayed(); assertThat(driver.findElement(By.tagName("h1")).getText(), is("Hello userName")); } } ``` -Há dois problemas com esta abordagem. +There are two problems with this approach. -* Não há separação entre o método de teste e os localizadores AUT (IDs neste exemplo); -ambos estão interligados em um único método. Se a IU da aplicação muda -seus identificadores, layout ou como um login é inserido e processado, o próprio teste -deve mudar. -* Os localizadores do ID estariam espalhados em vários testes, em todos os testes que precisassem -usar esta página de login. +* There is no separation between the test method and the AUT’s locators (IDs in +this example); both are intertwined in a single method. If the AUT’s UI changes +its identifiers, layout, or how a login is input and processed, the test itself +must change. +* The ID-locators would be spread in multiple tests, in all tests that had to +use this login page. -Aplicando as técnicas de objeto de página, este exemplo poderia ser reescrito assim -no exemplo a seguir de um objeto de página para uma página de Sign-in. +Applying the page object techniques, this example could be rewritten like this +in the following example of a page object for a Sign-in page. ```java import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; /** - * Page Object encapsula a página de login. + * Page Object encapsulates the Sign-in page. */ public class SignInPage { protected WebDriver driver; @@ -86,14 +97,14 @@ public class SignInPage { public SignInPage(WebDriver driver){ this.driver = driver; - if (!driver.getTitle().equals("Sign In Page")) { + if (!driver.getTitle().equals("Sign In Page")) { throw new IllegalStateException("This is not Sign In Page," + " current page is: " + driver.getCurrentUrl()); } } /** - * Login como um usuário válido + * Login as valid user * * @param userName * @param password @@ -108,14 +119,14 @@ public class SignInPage { } ``` -e o objeto de página de uma página inicial pode ter a seguinte aparência. +and page object for a Home page could look like this. ```java import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; /** - * Page Object encapsula a Home Page + * Page Object encapsulates the Home Page */ public class HomePage { protected WebDriver driver; @@ -141,16 +152,16 @@ public class HomePage { } public HomePage manageProfile() { - // Encapsulamento da página para gerenciar a funcionalidade do perfil + // Page encapsulation to manage profile functionality return new HomePage(driver); } - /* Mais métodos fornecendo o serviços representados pela Home Page - do usuário logado. Esses métodos por sua vez podem retornar mais Page Objects - por exemplo clicar no botão Compor Email poderia retornar um objeto ComposeMail */ + /* More methods offering the services represented by Home Page + of Logged User. These methods in turn might return more Page Objects + for example click on Compose mail button could return ComposeMail class object */ } ``` -Portanto, agora, o teste de login usaria esses dois objetos de página da seguinte maneira. +So now, the login test would use these two page objects as follows. ```java /*** @@ -168,36 +179,322 @@ public class TestLogin { } ``` -Há muita flexibilidade em como os objetos de página podem ser projetados, mas -existem algumas regras básicas para obter a manutenção desejada de seu -código de teste. - -Os próprios objetos de página nunca devem fazer verificações ou afirmações. Isto é -parte do seu teste e deve estar sempre dentro do código do teste, nunca em um objeto de página. -O objeto da página conterá a representação da página, e o -serviços que a página fornece por meio de métodos, mas nenhum código relacionado ao que está sendo -testado deve estar dentro do objeto de página. - -Há uma única verificação que pode e deve estar dentro do objeto de página e que é para verificar se a página -e, possivelmente, elementos críticos em a página, foram carregados corretamente. -Esta verificação deve ser feita enquanto instanciar o objeto de página. -Nos exemplos acima, ambos SignInPage e os construtores da HomePage verificam se a página -esperada está disponível e pronta para solicitações do teste. - -Um objeto de página não precisa necessariamente representar todas as partes da página em si. -Os mesmos princípios usados para objetos de página podem ser usados para -criar "Objetos de _Componente_ de Página" que representam pedaços discretos da -página e podem ser incluídos em objetos de página. Esses objetos de componentes podem -fornecer referências aos elementos dentro desses blocos discretos, e -métodos para utilizar a funcionalidade fornecida por eles. Você também pode -aninhar objetos de componentes dentro de outros objetos de componentes para páginas mais complexas. -Se uma página na aplicação tem vários componentes, ou -componentes usados em todo o site (por exemplo, uma barra de navegação), então -pode melhorar a manutenção e reduzir a duplicação de código. - -Existem outros padrões de design que também podem ser usados em testes. Alguns usam um -Page Factory para instanciar seus objetos de página. Discutir tudo isso é -além do escopo deste guia do usuário. Aqui, queremos apenas apresentar o -conceitos para tornar o leitor ciente de algumas coisas que podem ser feitas. Como -foi mencionado anteriormente, muitos escreveram sobre este tópico e nós encorajamos o -leitor para pesquisar blogs sobre esses tópicos. +There is a lot of flexibility in how the page objects may be designed, but +there are a few basic rules for getting the desired maintainability of your +test code. + +## Assertions in Page Objects +Page objects themselves should never make verifications or assertions. This is +part of your test and should always be within the test’s code, never in an page +object. The page object will contain the representation of the page, and the +services the page provides via methods but no code related to what is being +tested should be within the page object. + +There is one, single, verification which can, and should, be within the page +object and that is to verify that the page, and possibly critical elements on +the page, were loaded correctly. This verification should be done while +instantiating the page object. In the examples above, both the SignInPage and +HomePage constructors check that the expected page is available and ready for +requests from the test. + +## Page Component Objects +A page object does not necessarily need to represent all the parts of a +page itself. The same principles used for page objects can be used to +create "Page _Component_ Objects" that represent discrete chunks of the +page and can be included in page objects. These component objects can +provide references to the elements inside those discrete chunks, and +methods to leverage the functionality provided by them. + +For example, a Product page has multiple products. + +```html + +
+ Products +
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+
+``` + +Each product is a component of the Products page. + + +```html + +
+
Backpack
+
+
$29.99
+ +
+
+``` + +The Product page HAS-A list of products. This relationship is called Composition. In simpler terms, something is _composed of_ another thing. + +```java +public abstract class BasePage { + protected WebDriver driver; + + public BasePage(WebDriver driver) { + this.driver = driver; + } +} + +// Page Object +public class ProductsPage extends BasePage { + public ProductsPage(WebDriver driver) { + super(driver); + // No assertions, throws an exception if the element is not loaded + new WebDriverWait(driver, Duration.ofSeconds(3)) + .until(d -> d.findElement(By.className​("header_container"))); + } + + // Returning a list of products is a service of the page + public List getProducts() { + return driver.findElements(By.className​("inventory_item")) + .stream() + .map(e -> new Product(e)) // Map WebElement to a product component + .toList(); + } + + // Return a specific product using a boolean-valued function (predicate) + // This is the behavioral Strategy Pattern from GoF + public Product getProduct(Predicate condition) { + return getProducts() + .stream() + .filter(condition) // Filter by product name or price + .findFirst() + .orElseThrow(); + } +} +``` + +The Product component object is used inside the Products page object. + +```java +public abstract class BaseComponent { + protected WebElement root; + + public BaseComponent(WebElement root) { + this.root = root; + } +} + +// Page Component Object +public class Product extends BaseComponent { + // The root element contains the entire component + public Product(WebElement root) { + super(root); // inventory_item + } + + public String getName() { + // Locating an element begins at the root of the component + return root.findElement(By.className("inventory_item_name")).getText(); + } + + public BigDecimal getPrice() { + return new BigDecimal( + root.findElement(By.className("inventory_item_price")) + .getText() + .replace("$", "") + ).setScale(2, RoundingMode.UNNECESSARY); // Sanitation and formatting + } + + public void addToCart() { + root.findElement(By.id("add-to-cart-backpack")).click(); + } +} +``` + +So now, the products test would use the page object and the page component object as follows. + +```java +public class ProductsTest { + @Test + public void testProductInventory() { + var productsPage = new ProductsPage(driver); + var products = productsPage.getProducts(); + assertEquals(6, products.size()); // expected, actual + } + + @Test + public void testProductPrices() { + var productsPage = new ProductsPage(driver); + + // Pass a lambda expression (predicate) to filter the list of products + // The predicate or "strategy" is the behavior passed as parameter + var backpack = productsPage.getProduct(p -> p.getName().equals("Backpack")); + var bikeLight = productsPage.getProduct(p -> p.getName().equals("Bike Light")); + + assertEquals(new BigDecimal("29.99"), backpack.getPrice()); + assertEquals(new BigDecimal("9.99"), bikeLight.getPrice()); + } +} +``` + +The page and component are represented by their own objects. Both objects only have methods for the **services** they offer, which matches the real-world application in object-oriented programming. + +You can even +nest component objects inside other component objects for more complex +pages. If a page in the AUT has multiple components, or common +components used throughout the site (e.g. a navigation bar), then it +may improve maintainability and reduce code duplication. + +## Other Design Patterns Used in Testing +There are other design patterns that also may be used in testing. Some use a +Page Factory for instantiating their page objects. Discussing all of these is +beyond the scope of this user guide. Here, we merely want to introduce the +concepts to make the reader aware of some of the things that can be done. As +was mentioned earlier, many have blogged on this topic and we encourage the +reader to search for blogs on these topics. + +## Implementation Notes + + +PageObjects can be thought of as facing in two directions simultaneously. Facing toward the developer of a test, they represent the **services** offered by a particular page. Facing away from the developer, they should be the only thing that has a deep knowledge of the structure of the HTML of a page (or part of a page) It's simplest to think of the methods on a Page Object as offering the "services" that a page offers rather than exposing the details and mechanics of the page. As an example, think of the inbox of any web-based email system. Amongst the services it offers are the ability to compose a new email, choose to read a single email, and list the subject lines of the emails in the inbox. How these are implemented shouldn't matter to the test. + +Because we're encouraging the developer of a test to try and think about the services they're interacting with rather than the implementation, PageObjects should seldom expose the underlying WebDriver instance. To facilitate this, methods on the PageObject should return other PageObjects. This means we can effectively model the user's journey through our application. It also means that should the way that pages relate to one another change (like when the login page asks the user to change their password the first time they log into a service when it previously didn't do that), simply changing the appropriate method's signature will cause the tests to fail to compile. Put another way; we can tell which tests would fail without needing to run them when we change the relationship between pages and reflect this in the PageObjects. + +One consequence of this approach is that it may be necessary to model (for example) both a successful and unsuccessful login; or a click could have a different result depending on the app's state. When this happens, it is common to have multiple methods on the PageObject: + +``` +public class LoginPage { + public HomePage loginAs(String username, String password) { + // ... clever magic happens here + } + + public LoginPage loginAsExpectingError(String username, String password) { + // ... failed login here, maybe because one or both of the username and password are wrong + } + + public String getErrorMessage() { + // So we can verify that the correct error is shown + } +} +``` + +The code presented above shows an important point: the tests, not the PageObjects, should be responsible for making assertions about the state of a page. For example: + +``` +public void testMessagesAreReadOrUnread() { + Inbox inbox = new Inbox(driver); + inbox.assertMessageWithSubjectIsUnread("I like cheese"); + inbox.assertMessageWithSubjectIsNotUnread("I'm not fond of tofu"); +} +``` + +could be re-written as: + +``` +public void testMessagesAreReadOrUnread() { + Inbox inbox = new Inbox(driver); + assertTrue(inbox.isMessageWithSubjectIsUnread("I like cheese")); + assertFalse(inbox.isMessageWithSubjectIsUnread("I'm not fond of tofu")); +} +``` + +Of course, as with every guideline, there are exceptions, and one that is commonly seen with PageObjects is to check that the WebDriver is on the correct page when we instantiate the PageObject. This is done in the example below. + +Finally, a PageObject need not represent an entire page. It may represent a section that appears frequently within a site or page, such as site navigation. The essential principle is that there is only one place in your test suite with knowledge of the structure of the HTML of a particular (part of a) page. + +## Summary + +* The public methods represent the services that the page offers +* Try not to expose the internals of the page +* Generally don't make assertions +* Methods return other PageObjects +* Need not represent an entire page +* Different results for the same action are modelled as different methods + +## Example + +``` +public class LoginPage { + private final WebDriver driver; + + public LoginPage(WebDriver driver) { + this.driver = driver; + + // Check that we're on the right page. + if (!"Login".equals(driver.getTitle())) { + // Alternatively, we could navigate to the login page, perhaps logging out first + throw new IllegalStateException("This is not the login page"); + } + } + + // The login page contains several HTML elements that will be represented as WebElements. + // The locators for these elements should only be defined once. + By usernameLocator = By.id("username"); + By passwordLocator = By.id("passwd"); + By loginButtonLocator = By.id("login"); + + // The login page allows the user to type their username into the username field + public LoginPage typeUsername(String username) { + // This is the only place that "knows" how to enter a username + driver.findElement(usernameLocator).sendKeys(username); + + // Return the current page object as this action doesn't navigate to a page represented by another PageObject + return this; + } + + // The login page allows the user to type their password into the password field + public LoginPage typePassword(String password) { + // This is the only place that "knows" how to enter a password + driver.findElement(passwordLocator).sendKeys(password); + + // Return the current page object as this action doesn't navigate to a page represented by another PageObject + return this; + } + + // The login page allows the user to submit the login form + public HomePage submitLogin() { + // This is the only place that submits the login form and expects the destination to be the home page. + // A seperate method should be created for the instance of clicking login whilst expecting a login failure. + driver.findElement(loginButtonLocator).submit(); + + // Return a new page object representing the destination. Should the login page ever + // go somewhere else (for example, a legal disclaimer) then changing the method signature + // for this method will mean that all tests that rely on this behaviour won't compile. + return new HomePage(driver); + } + + // The login page allows the user to submit the login form knowing that an invalid username and / or password were entered + public LoginPage submitLoginExpectingFailure() { + // This is the only place that submits the login form and expects the destination to be the login page due to login failure. + driver.findElement(loginButtonLocator).submit(); + + // Return a new page object representing the destination. Should the user ever be navigated to the home page after submiting a login with credentials + // expected to fail login, the script will fail when it attempts to instantiate the LoginPage PageObject. + return new LoginPage(driver); + } + + // Conceptually, the login page offers the user the service of being able to "log into" + // the application using a user name and password. + public HomePage loginAs(String username, String password) { + // The PageObject methods that enter username, password & submit login have already defined and should not be repeated here. + typeUsername(username); + typePassword(password); + return submitLogin(); + } +} + +``` + + +## Support in WebDriver + +There is a PageFactory in the support package that provides support for this pattern and helps to remove some boiler-plate code from your Page Objects at the same time. diff --git a/website_and_docs/content/documentation/test_practices/encouraged/page_object_models.zh-cn.md b/website_and_docs/content/documentation/test_practices/encouraged/page_object_models.zh-cn.md index a84175df2f8c..d8be43e62da9 100644 --- a/website_and_docs/content/documentation/test_practices/encouraged/page_object_models.zh-cn.md +++ b/website_and_docs/content/documentation/test_practices/encouraged/page_object_models.zh-cn.md @@ -9,20 +9,43 @@ aliases: [ ] --- - -PO(page object)设计模式是在自动化中已经流行起来的一种易于维护和减少代码的设计模式. 在自动化测试中, PO对象作为一个与页面交互的接口. -测试中需要与页面的UI进行交互时, 便调用PO的方法. 这样做的好处是, 如果页面的UI发生了更改,那么测试用例本身不需要更改, 只需更改PO中的代码即可. - -PO设计模式具有以下优点: - -* 测试代码与页面的定位代码(如定位器或者其他的映射)相分离. -* 该页面提供的方法或元素在一个独立的类中, 而不是将这些方法或元素分散在整个测试中. - -这允许在一个地方修改由于UI变化所带来的所有修改. 随着这种"测试设计模式"的广泛使用, 可以在众多博客中找到有关此技术的有用信息. -我们鼓励希望了解更多信息的读者在互联网上搜索有关此主题的博客. 许多人已经写过这种设计模式, 并且可以提供超出本用户指南范围的有用提示. -不过, 为了让您入门, 我们将通过一个简单的示例来说明页面对象. - -首先, 思考一个不使用PO模式的自动化测试的典型案例: +Note: this page has merged contents from multiple sources, including +the [Selenium wiki](https://github.com/SeleniumHQ/selenium/wiki/PageObjects) + +## Overview + +Within your web app's UI, there are areas where your tests interact with. +A Page Object only models these as objects within the test code. +This reduces the amount of duplicated code and means that if the UI changes, +the fix needs only to be applied in one place. + +Page Object is a Design Pattern that has become popular in test automation for +enhancing test maintenance and reducing code duplication. A page object is an +object-oriented class that serves as an interface to a page of your AUT. The +tests then use the methods of this page object class whenever they need to +interact with the UI of that page. The benefit is that if the UI changes for +the page, the tests themselves don’t need to change, only the code within the +page object needs to change. Subsequently, all changes to support that new UI +are located in one place. + +### Advantages + +* There is a clean separation between the test code and page-specific code, such as + locators (or their use if you’re using a UI Map) and layout. +* There is a single repository for the services or operations the page offers + rather than having these services scattered throughout the tests. + +In both cases, this allows any modifications required due to UI changes to all +be made in one place. Helpful information on this technique can be found on +numerous blogs as this ‘test design pattern’ is becoming widely used. We +encourage readers who wish to know more to search the internet for blogs +on this subject. Many have written on this design pattern and can provide +helpful tips beyond the scope of this user guide. To get you started, +we’ll illustrate page objects with a simple example. + +### Examples +First, consider an example, typical of test automation, that does not use a +page object: ```java /*** @@ -31,24 +54,29 @@ PO设计模式具有以下优点: public class Login { public void testLogin() { - // 在登录页面上填写登录数据 + // fill login data on sign-in page driver.findElement(By.name("user_name")).sendKeys("userName"); driver.findElement(By.name("password")).sendKeys("my supersecret password"); driver.findElement(By.name("sign-in")).click(); - // 登录后验证h1标签是否为Hello userName + // verify h1 tag is "Hello userName" after login driver.findElement(By.tagName("h1")).isDisplayed(); assertThat(driver.findElement(By.tagName("h1")).getText(), is("Hello userName")); } } ``` -这种方法有两个问题. +There are two problems with this approach. -* 测试方法与定位器 (在此实例中为By.name)耦合过于严重. 如果测试的用户界面更改了其定位器或登录名的输入和处理方式, 则测试本身必须进行更改. -* 在对登录页面的所有测试中, 同一个定位器会散布在其中. +* There is no separation between the test method and the AUT’s locators (IDs in +this example); both are intertwined in a single method. If the AUT’s UI changes +its identifiers, layout, or how a login is input and processed, the test itself +must change. +* The ID-locators would be spread in multiple tests, in all tests that had to +use this login page. -可以在以下登录页面的示例中应用PO设计模式重写此示例. +Applying the page object techniques, this example could be rewritten like this +in the following example of a page object for a Sign-in page. ```java import org.openqa.selenium.By; @@ -69,7 +97,7 @@ public class SignInPage { public SignInPage(WebDriver driver){ this.driver = driver; - if (!driver.getTitle().equals("Sign In Page")) { + if (!driver.getTitle().equals("Sign In Page")) { throw new IllegalStateException("This is not Sign In Page," + " current page is: " + driver.getCurrentUrl()); } @@ -91,7 +119,7 @@ public class SignInPage { } ``` -Home page的PO如下所示. +and page object for a Home page could look like this. ```java import org.openqa.selenium.By; @@ -127,12 +155,13 @@ public class HomePage { // Page encapsulation to manage profile functionality return new HomePage(driver); } - /* 提供登录用户主页所代表的服务的更多方法. 这些方法可能会返回更多页面对象. - 例如, 单击"撰写邮件"按钮可以返回ComposeMail类对象 */ + /* More methods offering the services represented by Home Page + of Logged User. These methods in turn might return more Page Objects + for example click on Compose mail button could return ComposeMail class object */ } ``` -那么, 接下来的登录测试用例将使用这两个页面对象. +So now, the login test would use these two page objects as follows. ```java /*** @@ -150,18 +179,322 @@ public class TestLogin { } ``` -PO的设计方式具有很大的灵活性, 但是有一些基本规则可以使测试代码具有理想的可维护性. +There is a lot of flexibility in how the page objects may be designed, but +there are a few basic rules for getting the desired maintainability of your +test code. + +## Assertions in Page Objects +Page objects themselves should never make verifications or assertions. This is +part of your test and should always be within the test’s code, never in an page +object. The page object will contain the representation of the page, and the +services the page provides via methods but no code related to what is being +tested should be within the page object. + +There is one, single, verification which can, and should, be within the page +object and that is to verify that the page, and possibly critical elements on +the page, were loaded correctly. This verification should be done while +instantiating the page object. In the examples above, both the SignInPage and +HomePage constructors check that the expected page is available and ready for +requests from the test. + +## Page Component Objects +A page object does not necessarily need to represent all the parts of a +page itself. The same principles used for page objects can be used to +create "Page _Component_ Objects" that represent discrete chunks of the +page and can be included in page objects. These component objects can +provide references to the elements inside those discrete chunks, and +methods to leverage the functionality provided by them. + +For example, a Product page has multiple products. + +```html + +
+ Products +
+ +
+
+
+
+
+
+
+
+
+
+
+
+
+
+``` + +Each product is a component of the Products page. + + +```html + +
+
Backpack
+
+
$29.99
+ +
+
+``` + +The Product page HAS-A list of products. This relationship is called Composition. In simpler terms, something is _composed of_ another thing. + +```java +public abstract class BasePage { + protected WebDriver driver; + + public BasePage(WebDriver driver) { + this.driver = driver; + } +} + +// Page Object +public class ProductsPage extends BasePage { + public ProductsPage(WebDriver driver) { + super(driver); + // No assertions, throws an exception if the element is not loaded + new WebDriverWait(driver, Duration.ofSeconds(3)) + .until(d -> d.findElement(By.className​("header_container"))); + } + + // Returning a list of products is a service of the page + public List getProducts() { + return driver.findElements(By.className​("inventory_item")) + .stream() + .map(e -> new Product(e)) // Map WebElement to a product component + .toList(); + } + + // Return a specific product using a boolean-valued function (predicate) + // This is the behavioral Strategy Pattern from GoF + public Product getProduct(Predicate condition) { + return getProducts() + .stream() + .filter(condition) // Filter by product name or price + .findFirst() + .orElseThrow(); + } +} +``` + +The Product component object is used inside the Products page object. + +```java +public abstract class BaseComponent { + protected WebElement root; + + public BaseComponent(WebElement root) { + this.root = root; + } +} + +// Page Component Object +public class Product extends BaseComponent { + // The root element contains the entire component + public Product(WebElement root) { + super(root); // inventory_item + } + + public String getName() { + // Locating an element begins at the root of the component + return root.findElement(By.className("inventory_item_name")).getText(); + } + + public BigDecimal getPrice() { + return new BigDecimal( + root.findElement(By.className("inventory_item_price")) + .getText() + .replace("$", "") + ).setScale(2, RoundingMode.UNNECESSARY); // Sanitation and formatting + } + + public void addToCart() { + root.findElement(By.id("add-to-cart-backpack")).click(); + } +} +``` + +So now, the products test would use the page object and the page component object as follows. + +```java +public class ProductsTest { + @Test + public void testProductInventory() { + var productsPage = new ProductsPage(driver); + var products = productsPage.getProducts(); + assertEquals(6, products.size()); // expected, actual + } + + @Test + public void testProductPrices() { + var productsPage = new ProductsPage(driver); + + // Pass a lambda expression (predicate) to filter the list of products + // The predicate or "strategy" is the behavior passed as parameter + var backpack = productsPage.getProduct(p -> p.getName().equals("Backpack")); + var bikeLight = productsPage.getProduct(p -> p.getName().equals("Bike Light")); + + assertEquals(new BigDecimal("29.99"), backpack.getPrice()); + assertEquals(new BigDecimal("9.99"), bikeLight.getPrice()); + } +} +``` + +The page and component are represented by their own objects. Both objects only have methods for the **services** they offer, which matches the real-world application in object-oriented programming. + +You can even +nest component objects inside other component objects for more complex +pages. If a page in the AUT has multiple components, or common +components used throughout the site (e.g. a navigation bar), then it +may improve maintainability and reduce code duplication. + +## Other Design Patterns Used in Testing +There are other design patterns that also may be used in testing. Some use a +Page Factory for instantiating their page objects. Discussing all of these is +beyond the scope of this user guide. Here, we merely want to introduce the +concepts to make the reader aware of some of the things that can be done. As +was mentioned earlier, many have blogged on this topic and we encourage the +reader to search for blogs on these topics. + +## Implementation Notes + + +PageObjects can be thought of as facing in two directions simultaneously. Facing toward the developer of a test, they represent the **services** offered by a particular page. Facing away from the developer, they should be the only thing that has a deep knowledge of the structure of the HTML of a page (or part of a page) It's simplest to think of the methods on a Page Object as offering the "services" that a page offers rather than exposing the details and mechanics of the page. As an example, think of the inbox of any web-based email system. Amongst the services it offers are the ability to compose a new email, choose to read a single email, and list the subject lines of the emails in the inbox. How these are implemented shouldn't matter to the test. + +Because we're encouraging the developer of a test to try and think about the services they're interacting with rather than the implementation, PageObjects should seldom expose the underlying WebDriver instance. To facilitate this, methods on the PageObject should return other PageObjects. This means we can effectively model the user's journey through our application. It also means that should the way that pages relate to one another change (like when the login page asks the user to change their password the first time they log into a service when it previously didn't do that), simply changing the appropriate method's signature will cause the tests to fail to compile. Put another way; we can tell which tests would fail without needing to run them when we change the relationship between pages and reflect this in the PageObjects. + +One consequence of this approach is that it may be necessary to model (for example) both a successful and unsuccessful login; or a click could have a different result depending on the app's state. When this happens, it is common to have multiple methods on the PageObject: + +``` +public class LoginPage { + public HomePage loginAs(String username, String password) { + // ... clever magic happens here + } + + public LoginPage loginAsExpectingError(String username, String password) { + // ... failed login here, maybe because one or both of the username and password are wrong + } + + public String getErrorMessage() { + // So we can verify that the correct error is shown + } +} +``` + +The code presented above shows an important point: the tests, not the PageObjects, should be responsible for making assertions about the state of a page. For example: + +``` +public void testMessagesAreReadOrUnread() { + Inbox inbox = new Inbox(driver); + inbox.assertMessageWithSubjectIsUnread("I like cheese"); + inbox.assertMessageWithSubjectIsNotUnread("I'm not fond of tofu"); +} +``` + +could be re-written as: + +``` +public void testMessagesAreReadOrUnread() { + Inbox inbox = new Inbox(driver); + assertTrue(inbox.isMessageWithSubjectIsUnread("I like cheese")); + assertFalse(inbox.isMessageWithSubjectIsUnread("I'm not fond of tofu")); +} +``` + +Of course, as with every guideline, there are exceptions, and one that is commonly seen with PageObjects is to check that the WebDriver is on the correct page when we instantiate the PageObject. This is done in the example below. + +Finally, a PageObject need not represent an entire page. It may represent a section that appears frequently within a site or page, such as site navigation. The essential principle is that there is only one place in your test suite with knowledge of the structure of the HTML of a particular (part of a) page. -PO本身绝不应进行判断或断言. 判断和断言是测试的一部分, 应始终在测试的代码内, 而不是在PO中. -PO用来包含页面的表示形式, 以及页面通过方法提供的服务, 但是与PO无关的测试代码不应包含在其中. +## Summary -实例化PO时, 应进行一次验证, 即验证页面以及页面上可能的关键元素是否已正确加载. -在上面的示例中, SignInPage和HomePage的构造函数均检查预期的页面是否可用并准备接受测试请求. +* The public methods represent the services that the page offers +* Try not to expose the internals of the page +* Generally don't make assertions +* Methods return other PageObjects +* Need not represent an entire page +* Different results for the same action are modelled as different methods + +## Example + +``` +public class LoginPage { + private final WebDriver driver; + + public LoginPage(WebDriver driver) { + this.driver = driver; + + // Check that we're on the right page. + if (!"Login".equals(driver.getTitle())) { + // Alternatively, we could navigate to the login page, perhaps logging out first + throw new IllegalStateException("This is not the login page"); + } + } + + // The login page contains several HTML elements that will be represented as WebElements. + // The locators for these elements should only be defined once. + By usernameLocator = By.id("username"); + By passwordLocator = By.id("passwd"); + By loginButtonLocator = By.id("login"); + + // The login page allows the user to type their username into the username field + public LoginPage typeUsername(String username) { + // This is the only place that "knows" how to enter a username + driver.findElement(usernameLocator).sendKeys(username); + + // Return the current page object as this action doesn't navigate to a page represented by another PageObject + return this; + } + + // The login page allows the user to type their password into the password field + public LoginPage typePassword(String password) { + // This is the only place that "knows" how to enter a password + driver.findElement(passwordLocator).sendKeys(password); + + // Return the current page object as this action doesn't navigate to a page represented by another PageObject + return this; + } + + // The login page allows the user to submit the login form + public HomePage submitLogin() { + // This is the only place that submits the login form and expects the destination to be the home page. + // A seperate method should be created for the instance of clicking login whilst expecting a login failure. + driver.findElement(loginButtonLocator).submit(); + + // Return a new page object representing the destination. Should the login page ever + // go somewhere else (for example, a legal disclaimer) then changing the method signature + // for this method will mean that all tests that rely on this behaviour won't compile. + return new HomePage(driver); + } + + // The login page allows the user to submit the login form knowing that an invalid username and / or password were entered + public LoginPage submitLoginExpectingFailure() { + // This is the only place that submits the login form and expects the destination to be the login page due to login failure. + driver.findElement(loginButtonLocator).submit(); + + // Return a new page object representing the destination. Should the user ever be navigated to the home page after submiting a login with credentials + // expected to fail login, the script will fail when it attempts to instantiate the LoginPage PageObject. + return new LoginPage(driver); + } + + // Conceptually, the login page offers the user the service of being able to "log into" + // the application using a user name and password. + public HomePage loginAs(String username, String password) { + // The PageObject methods that enter username, password & submit login have already defined and should not be repeated here. + typeUsername(username); + typePassword(password); + return submitLogin(); + } +} + +``` -PO不一定需要代表整个页面. PO设计模式可用于表示页面上的组件. -如果自动化测试中的页面包含多个组件, 则每个组件都有单独的页面对象, 则可以提高可维护性. -还有其他设计模式也可以在测试中使用. 一些使用页面工厂实例化其页面对象. 讨论所有这些都不在本用户指南的范围之内. -在这里, 我们只想介绍一些概念, 以使读者了解可以完成的一些事情. -如前所述, 许多人都在此主题上写博客, 我们鼓励读者搜索有关这些主题的博客. +## Support in WebDriver +There is a PageFactory in the support package that provides support for this pattern and helps to remove some boiler-plate code from your Page Objects at the same time.