Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 7bf0cb9

Browse files
committedMay 21, 2025·
docs: update all relevant page_object_models.*.md
1 parent 70431fc commit 7bf0cb9

File tree

3 files changed

+194
-132
lines changed

3 files changed

+194
-132
lines changed
 

‎website_and_docs/content/documentation/test_practices/encouraged/page_object_models.ja.md

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ A Page Object only models these as objects within the test code.
1919
This reduces the amount of duplicated code and means that if the UI changes,
2020
the fix needs only to be applied in one place.
2121

22-
Page Object is a Design Pattern that has become popular in test automation for
22+
Page Object Model is a Design Pattern that has become popular in test automation for
2323
enhancing test maintenance and reducing code duplication. A page object is an
2424
object-oriented class that serves as an interface to a page of your AUT. The
2525
tests then use the methods of this page object class whenever they need to
@@ -44,6 +44,7 @@ helpful tips beyond the scope of this user guide. To get you started,
4444
we’ll illustrate page objects with a simple example.
4545

4646
### Examples
47+
4748
First, consider an example, typical of test automation, that does not use a
4849
page object:
4950

@@ -75,7 +76,7 @@ must change.
7576
* The ID-locators would be spread in multiple tests, in all tests that had to
7677
use this login page.
7778

78-
Applying the page object techniques, this example could be rewritten like this
79+
Applying the page object model, this example could be rewritten like this
7980
in the following example of a page object for a Sign-in page.
8081

8182
```java
@@ -184,6 +185,7 @@ there are a few basic rules for getting the desired maintainability of your
184185
test code.
185186

186187
## Assertions in Page Objects
188+
187189
Page objects themselves should never make verifications or assertions. This is
188190
part of your test and should always be within the test’s code, never in a page
189191
object. The page object will contain the representation of the page, and the
@@ -198,6 +200,7 @@ HomePage constructors check that the expected page is available and ready for
198200
requests from the test.
199201

200202
## Page Component Objects
203+
201204
A page object does not necessarily need to represent all the parts of a
202205
page itself. This was [noted by Martin Fowler](https://martinfowler.com/bliki/PageObject.html#footnote-panel-object) in the early days, while first coining the term "panel objects".
203206

@@ -280,7 +283,7 @@ public class ProductsPage extends BasePage {
280283
.stream()
281284
.filter(condition) // Filter by product name or price
282285
.findFirst()
283-
.orElseThrow();
286+
.orElseThrow(() -> new RuntimeException("Product not found")); // Error thrown during actual test run
284287
}
285288
}
286289
```
@@ -348,7 +351,7 @@ public class ProductsTest {
348351
}
349352
```
350353

351-
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.
354+
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 as is the core principle of object-oriented programming. When applications are built, they are not made of a massive page entity. They are built with components contained in a page. Page Component Objects implement the same approach.
352355

353356
You can even
354357
nest component objects inside other component objects for more complex
@@ -357,6 +360,7 @@ components used throughout the site (e.g. a navigation bar), then it
357360
may improve maintainability and reduce code duplication.
358361

359362
## Other Design Patterns Used in Testing
363+
360364
There are other design patterns that also may be used in testing. Discussing all of these is
361365
beyond the scope of this user guide. Here, we merely want to introduce the
362366
concepts to make the reader aware of some of the things that can be done. As
@@ -365,12 +369,11 @@ reader to search for blogs on these topics.
365369

366370
## Implementation Notes
367371

372+
Page Objects 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.
368373

369-
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.
370-
371-
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.
374+
Because we're encouraging the developer of a test to try and think about the services they're interacting with rather than the implementation, Page Objects should seldom expose the underlying WebDriver instance. To facilitate this, **methods on the Page Object may return another Page Object, another Page Component Object, or even itself (this)**. 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 Page Objects.
372375

373-
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:
376+
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 Page Object:
374377

375378
```java
376379
public class LoginPage {
@@ -388,7 +391,7 @@ public class LoginPage {
388391
}
389392
```
390393

391-
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:
394+
The code presented above shows an important point: the tests, not the Page Objects, should be responsible for making assertions about the state of a page. For example:
392395

393396
```java
394397
public void testMessagesAreReadOrUnread() {
@@ -408,17 +411,17 @@ public void testMessagesAreReadOrUnread() {
408411
}
409412
```
410413

411-
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.
414+
Of course, as with every guideline, there are exceptions, and one that is commonly seen with Page Objects is to check that the WebDriver is on the correct page when we instantiate the Page Object. This is done in the example below.
412415

413-
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.
416+
Finally, a Page Object need not represent an entire page and can be composed of Page Object Components. These components 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.
414417

415418
## Summary
416419

417-
* The public methods represent the services that the page offers
418-
* Try not to expose the internals of the page
420+
* The public methods represent the services that the page or component offers
421+
* Try not to expose the internals of the page or component
419422
* Generally don't make assertions
420-
* Methods return other PageObjects
421-
* Need not represent an entire page
423+
* Methods return other Page Objects, Page Component Objects, or optionally themselves (for fluent syntax)
424+
* Need not represent an entire page all the time
422425
* Different results for the same action are modelled as different methods
423426

424427
## Example
@@ -492,4 +495,4 @@ public class LoginPage {
492495
return submitLogin();
493496
}
494497
}
495-
```
498+
```

‎website_and_docs/content/documentation/test_practices/encouraged/page_object_models.pt-br.md

Lines changed: 156 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -9,57 +9,82 @@ aliases: [
99
]
1010
---
1111

12-
Nota: esta página reuniu conteúdos de várias fontes, incluindo
13-
o [Selenium wiki](https://github.com/SeleniumHQ/selenium/wiki/PageObjects)
12+
Note: this page has merged contents from multiple sources, including
13+
the [Selenium wiki](https://github.com/SeleniumHQ/selenium/wiki/PageObjects)
1414

15-
## Visão geral
15+
## Overview
1616

17-
Dentro da interface de usuário (UI) do seu aplicativo web, existem áreas com as quais seus testes interagem. O Page Object modela apenas essas áreas como objetos dentro do código de teste. Isso reduz a quantidade de código duplicado e significa que, se a UI mudar, a correção precisará ser aplicada apenas em um lugar.
17+
Within your web app's UI, there are areas where your tests interact with.
18+
A Page Object only models these as objects within the test code.
19+
This reduces the amount of duplicated code and means that if the UI changes,
20+
the fix needs only to be applied in one place.
1821

19-
Page Object é um padrão de design (Design Pattern) que se tornou popular na automação de testes para melhorar a manutenção de testes e reduzir a duplicação de código. Page Object é uma classe orientada a objetos que serve como interface para uma página do seu AUT (Aplicativo Sob Teste). Os testes usam então os métodos desta classe de Page Object sempre que precisam interagir com a UI dessa página. A vantagem é que, se a UI da página mudar, os próprios testes não precisam mudar, apenas o código dentro do Page Object precisa mudar. Subsequentemente, todas as mudanças para suportar essa nova UI estão localizadas em um lugar.
22+
Page Object Model is a Design Pattern that has become popular in test automation for
23+
enhancing test maintenance and reducing code duplication. A page object is an
24+
object-oriented class that serves as an interface to a page of your AUT. The
25+
tests then use the methods of this page object class whenever they need to
26+
interact with the UI of that page. The benefit is that if the UI changes for
27+
the page, the tests themselves don’t need to change, only the code within the
28+
page object needs to change. Subsequently, all changes to support that new UI
29+
are located in one place.
2030

21-
### Vantagens
31+
### Advantages
2232

23-
* Existe uma separação bem definida entre o código do teste e o código da página especifica.
24-
* Existe um repositório único para os serviços ou operações que a página oferece, em vez de ter esses serviços espalhados pelos testes.
33+
* There is a clean separation between the test code and page-specific code, such as
34+
locators (or their use if you’re using a UI Map) and layout.
35+
* There is a single repository for the services or operations the page offers
36+
rather than having these services scattered throughout the tests.
2537

26-
Em ambos os casos, isso permite que quaisquer modificações necessárias devido a mudanças na UI sejam feitas em um lugar somente. Informações úteis sobre esta técnica podem ser encontradas em vários blogs, pois este 'padrão de design de teste (test design pattern)' está se tornando amplamente utilizado. Encorajamos os leitores que desejam saber mais a pesquisar na internet por blogs sobre este assunto. Muitos já escreveram sobre este padrão de design e podem fornecer dicas úteis além do escopo deste guia do usuário. Para começar, vamos ilustrar Page Object com um exemplo simples.
38+
In both cases, this allows any modifications required due to UI changes to all
39+
be made in one place. Helpful information on this technique can be found on
40+
numerous blogs as this ‘test design pattern’ is becoming widely used. We
41+
encourage readers who wish to know more to search the internet for blogs
42+
on this subject. Many have written on this design pattern and can provide
43+
helpful tips beyond the scope of this user guide. To get you started,
44+
we’ll illustrate page objects with a simple example.
2745

28-
### Exemplos
29-
Primeiro, considere um exemplo, típico da automação de testes, que não usa um objeto de página:
46+
### Examples
47+
48+
First, consider an example, typical of test automation, that does not use a
49+
page object:
3050

3151
```java
3252
/***
33-
* Testes da funcionalidade de login
53+
* Tests login feature
3454
*/
3555
public class Login {
3656

3757
public void testLogin() {
38-
// preencha os dados de login na página de entrada
58+
// fill login data on sign-in page
3959
driver.findElement(By.name("user_name")).sendKeys("userName");
4060
driver.findElement(By.name("password")).sendKeys("my supersecret password");
4161
driver.findElement(By.name("sign-in")).click();
4262

43-
// verifique se a tag h1 é "Hello userName" após o login
63+
// verify h1 tag is "Hello userName" after login
4464
driver.findElement(By.tagName("h1")).isDisplayed();
4565
assertThat(driver.findElement(By.tagName("h1")).getText(), is("Hello userName"));
4666
}
4767
}
4868
```
4969

50-
Existem dois problemas com essa abordagem.
70+
There are two problems with this approach.
5171

52-
* Não há separação entre o método de teste e os localizadores do aplicativo em teste (IDs neste exemplo); ambos estão entrelaçados em um único método. Se a UI do aplicativo em teste muda seus identificadores, layout ou como um login é inserido e processado, o próprio teste deve mudar.
53-
* Os localizadores ID estariam espalhados em vários testes, em todos os testes que tivessem que usar esta página de login.
72+
* There is no separation between the test method and the AUT’s locators (IDs in
73+
this example); both are intertwined in a single method. If the AUT’s UI changes
74+
its identifiers, layout, or how a login is input and processed, the test itself
75+
must change.
76+
* The ID-locators would be spread in multiple tests, in all tests that had to
77+
use this login page.
5478

55-
Aplicando as técnicas de Page Object, este exemplo poderia ser reescrito da seguinte forma no exemplo para uma página de login.
79+
Applying the page object model, this example could be rewritten like this
80+
in the following example of a page object for a Sign-in page.
5681

5782
```java
5883
import org.openqa.selenium.By;
5984
import org.openqa.selenium.WebDriver;
6085

6186
/**
62-
* Page Object encapsula a página de login.
87+
* Page Object encapsulates the Sign-in page.
6388
*/
6489
public class SignInPage {
6590
protected WebDriver driver;
@@ -80,11 +105,11 @@ public class SignInPage {
80105
}
81106

82107
/**
83-
* Faz login como um usuário válido
108+
* Login as valid user
84109
*
85110
* @param userName
86111
* @param password
87-
* @return pbjeto da Pagina Inicial
112+
* @return HomePage object
88113
*/
89114
public HomePage loginValidUser(String userName, String password) {
90115
driver.findElement(usernameBy).sendKeys(userName);
@@ -95,14 +120,14 @@ public class SignInPage {
95120
}
96121
```
97122

98-
E o objeto de página para uma página inicial poderia parecer assim.
123+
and page object for a Home page could look like this.
99124

100125
```java
101126
import org.openqa.selenium.By;
102127
import org.openqa.selenium.WebDriver;
103128

104129
/**
105-
* Page Object encapsula a Página Inicial
130+
* Page Object encapsulates the Home Page
106131
*/
107132
public class HomePage {
108133
protected WebDriver driver;
@@ -119,27 +144,29 @@ public class HomePage {
119144
}
120145

121146
/**
122-
* Obtém a mensagem (tag h1)
147+
* Get message (h1 tag)
123148
*
124-
* @return String da mensagem de texto
149+
* @return String message text
125150
*/
126151
public String getMessageText() {
127152
return driver.findElement(messageBy).getText();
128153
}
129154

130155
public HomePage manageProfile() {
131-
// Encapsulamento da página para gerenciar a funcionalidade do perfil
156+
// Page encapsulation to manage profile functionality
132157
return new HomePage(driver);
133158
}
134-
/* Mais métodos que oferecem os serviços representados pela Página inicial do usuário logado. Estes métodos por sua vez podem retornar mais Page Object, por exemplo, clicar no botão "Compor email" pode retornar um objeto da classe ComposeMail */
159+
/* More methods offering the services represented by Home Page
160+
of Logged User. These methods in turn might return more Page Objects
161+
for example click on Compose mail button could return ComposeMail class object */
135162
}
136163
```
137164

138-
Então agora, o teste de login usaria esses dois objetos de página da seguinte maneira.
165+
So now, the login test would use these two page objects as follows.
139166

140167
```java
141168
/***
142-
* Testes da funcionalidade de login
169+
* Tests login feature
143170
*/
144171
public class TestLogin {
145172

@@ -153,22 +180,40 @@ public class TestLogin {
153180
}
154181
```
155182

156-
Há muita flexibilidade em como o Page Object pode ser projetado, mas existem algumas regras básicas para obter a manutenibilidade desejada do seu código de teste.
183+
There is a lot of flexibility in how the page objects may be designed, but
184+
there are a few basic rules for getting the desired maintainability of your
185+
test code.
186+
187+
## Assertions in Page Objects
188+
189+
Page objects themselves should never make verifications or assertions. This is
190+
part of your test and should always be within the test’s code, never in a page
191+
object. The page object will contain the representation of the page, and the
192+
services the page provides via methods but no code related to what is being
193+
tested should be within the page object.
157194

158-
## Afirmações em Page Objects
159-
Os Page Objects em si nunca devem fazer verificações ou afirmações. Isso faz parte do seu teste e sempre deve estar dentro do código do teste, nunca em um objeto de página. O objeto de página conterá a representação da página e os 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.
195+
There is one, single, verification which can, and should, be within the page
196+
object and that is to verify that the page, and possibly critical elements on
197+
the page, were loaded correctly. This verification should be done while
198+
instantiating the page object. In the examples above, both the SignInPage and
199+
HomePage constructors check that the expected page is available and ready for
200+
requests from the test.
160201

161-
Há uma única verificação que pode e deve estar dentro do objeto de página, e isso é para verificar se a página e possivelmente elementos críticos na página, foram carregados corretamente. Essa verificação deve ser feita ao instanciar o objeto de página. Nos exemplos acima, tanto os construtores SignInPage quanto HomePage verificam se a página esperada está disponível e pronta para solicitações do teste.
202+
## Page Component Objects
162203

163-
## Objetos Componentes de Página (Page Component Object)
164-
Page Object não precisa necessariamente representar todas as partes de uma página. Isso foi [notado por Martin Fowler](https://martinfowler.com/bliki/PageObject.html#footnote-panel-object) nos primeiros dias, enquanto cunhava o termo "objetos de painel (panel objects)".
204+
A page object does not necessarily need to represent all the parts of a
205+
page itself. This was [noted by Martin Fowler](https://martinfowler.com/bliki/PageObject.html#footnote-panel-object) in the early days, while first coining the term "panel objects".
165206

166-
Os mesmos princípios usados para objetos de página podem ser usados para criar "Objetos Componente de Página", como foi chamado mais tarde, que representam partes discretas da página e podem ser incluídos em Page Object. Esses objetos de componente podem fornecer referências aos elementos dentro dessas partes discretas e métodos para aproveitar a funcionalidade ou comportamento fornecidos por eles.
207+
The same principles used for page objects can be used to
208+
create "Page _Component_ Objects", as it was later called, that represent discrete chunks of the
209+
page and **can be included in page objects**. These component objects can
210+
provide references to the elements inside those discrete chunks, and
211+
methods to leverage the functionality or behavior provided by them.
167212

168-
Por exemplo, uma página de Produtos tem vários produtos.
213+
For example, a Products page has multiple products.
169214

170215
```html
171-
<!-- Página de Produtos -->
216+
<!-- Products Page -->
172217
<div class="header_container">
173218
<span class="title">Products</span>
174219
</div>
@@ -189,7 +234,8 @@ Por exemplo, uma página de Produtos tem vários produtos.
189234
</div>
190235
```
191236

192-
Cada produto é um componente da página de Produtos.
237+
Each product is a component of the Products page.
238+
193239

194240
```html
195241
<!-- Inventory Item -->
@@ -202,7 +248,7 @@ Cada produto é um componente da página de Produtos.
202248
</div>
203249
```
204250

205-
A página de Produtos "TEM-UMA (HAS-A)" lista de produtos. This object relationship is called Composition. Essa relação de objeto é chamada de Composição. Em termos mais simples, algo é _composto de_ outra coisa.
251+
The Products page HAS-A list of products. This object relationship is called Composition. In simpler terms, something is _composed of_ another thing.
206252

207253
```java
208254
public abstract class BasePage {
@@ -217,32 +263,32 @@ public abstract class BasePage {
217263
public class ProductsPage extends BasePage {
218264
public ProductsPage(WebDriver driver) {
219265
super(driver);
220-
// Sem afirmações, lança uma exceção se o elemento não for carregado
266+
// No assertions, throws an exception if the element is not loaded
221267
new WebDriverWait(driver, Duration.ofSeconds(3))
222268
.until(d -> d.findElement(By.className​("header_container")));
223269
}
224270

225-
// Retornar uma lista de produtos é um serviço da página
271+
// Returning a list of products is a service of the page
226272
public List<Product> getProducts() {
227273
return driver.findElements(By.className​("inventory_item"))
228274
.stream()
229-
.map(e -> new Product(e)) // Mapeia WebElement para um componente do produto
275+
.map(e -> new Product(e)) // Map WebElement to a product component
230276
.toList();
231277
}
232278

233-
// Retorna um produto específico usando uma função booleana (predicado)
234-
// Este é o padrão de estratégia comportamental do GoF
279+
// Return a specific product using a boolean-valued function (predicate)
280+
// This is the behavioral Strategy Pattern from GoF
235281
public Product getProduct(Predicate<Product> condition) {
236282
return getProducts()
237283
.stream()
238-
.filter(condition) // Filtra por nome de produto ou preço
284+
.filter(condition) // Filter by product name or price
239285
.findFirst()
240-
.orElseThrow();
286+
.orElseThrow(() -> new RuntimeException("Product not found")); // Error thrown during actual test run
241287
}
242288
}
243289
```
244290

245-
O objeto do componente Produto é usado dentro do objeto de página Produtos.
291+
The Product component object is used inside the Products page object.
246292

247293
```java
248294
public abstract class BaseComponent {
@@ -253,15 +299,15 @@ public abstract class BaseComponent {
253299
}
254300
}
255301

256-
// Objeto Componente da Página (Page Component Object)
302+
// Page Component Object
257303
public class Product extends BaseComponent {
258-
// O elemento raiz contém todo o componente
304+
// The root element contains the entire component
259305
public Product(WebElement root) {
260306
super(root); // inventory_item
261307
}
262308

263309
public String getName() {
264-
// A localização de um elemento começa na raiz do componente
310+
// Locating an element begins at the root of the component
265311
return root.findElement(By.className("inventory_item_name")).getText();
266312
}
267313

@@ -270,7 +316,7 @@ public class Product extends BaseComponent {
270316
root.findElement(By.className("inventory_item_price"))
271317
.getText()
272318
.replace("$", "")
273-
).setScale(2, RoundingMode.UNNECESSARY); // Higienização e formatação
319+
).setScale(2, RoundingMode.UNNECESSARY); // Sanitation and formatting
274320
}
275321

276322
public void addToCart() {
@@ -279,23 +325,23 @@ public class Product extends BaseComponent {
279325
}
280326
```
281327

282-
Agora, o teste dos produtos usaria o Page Objecto e o Page Component Obeject da seguinte maneira.
328+
So now, the products test would use the page object and the page component object as follows.
283329

284330
```java
285331
public class ProductsTest {
286332
@Test
287333
public void testProductInventory() {
288334
var productsPage = new ProductsPage(driver); // page object
289335
var products = productsPage.getProducts();
290-
assertEquals(6, products.size()); // esperado, atual
336+
assertEquals(6, products.size()); // expected, actual
291337
}
292338

293339
@Test
294340
public void testProductPrices() {
295341
var productsPage = new ProductsPage(driver);
296342

297-
// Passa uma expressão lambda (predicado) para filtrar a lista de produtos
298-
// O predicado ou "estratégia" é o comportamento passado como parâmetro
343+
// Pass a lambda expression (predicate) to filter the list of products
344+
// The predicate or "strategy" is the behavior passed as parameter
299345
var backpack = productsPage.getProduct(p -> p.getName().equals("Backpack")); // page component object
300346
var bikeLight = productsPage.getProduct(p -> p.getName().equals("Bike Light"));
301347

@@ -305,38 +351,47 @@ public class ProductsTest {
305351
}
306352
```
307353

308-
A página e o componente são representados por seus próprios objetos. Ambos os objetos têm apenas métodos para os **serviços** que oferecem, o que corresponde à aplicação do mundo real na programação orientada a objetos.
354+
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 as is the core principle of object-oriented programming. When applications are built, they are not made of a massive page entity. They are built with components contained in a page. Page Component Objects implement the same approach.
355+
356+
You can even
357+
nest component objects inside other component objects for more complex
358+
pages. If a page in the AUT has multiple components, or common
359+
components used throughout the site (e.g. a navigation bar), then it
360+
may improve maintainability and reduce code duplication.
309361

310-
Você pode até aninhar objetos de componentes dentro de outros objetos de componentes para páginas mais complexas. Se uma página na AUT tiver vários componentes, ou componentes comuns usados em todo o site (por exemplo, uma barra de navegação), então isso pode melhorar a manutenibilidade e reduzir a duplicação de código.
362+
## Other Design Patterns Used in Testing
311363

312-
## Outros Padrões de Projeto (Design Patterns) Usados em Testes
313-
Existem outros padrões de projeto que também podem ser usados em testes. Discutir todos esses está além do escopo deste guia do usuário. Aqui, apenas queremos introduzir os conceitos para tornar o leitor ciente de algumas das coisas que podem ser feitas. Como foi mencionado anteriormente, muitos escreveram sobre este tópico e encorajamos o leitor a procurar blogs sobre esses tópicos.
364+
There are other design patterns that also may be used in testing. Discussing all of these is
365+
beyond the scope of this user guide. Here, we merely want to introduce the
366+
concepts to make the reader aware of some of the things that can be done. As
367+
was mentioned earlier, many have blogged on this topic and we encourage the
368+
reader to search for blogs on these topics.
314369

315-
## Notas de Implementação
370+
## Implementation Notes
316371

317-
Page Objects podem ser pensados como se estivessem voltados para duas direções simultaneamente. Voltado para o desenvolvedor de um teste, eles representam os **serviços** oferecidos por uma página específica. Virado para longe do desenvolvedor, eles devem ser a única coisa que tem um conhecimento profundo da estrutura do HTML de uma página (ou parte de uma página). É mais simples pensar nos métodos de um Page Object como oferecendo os "serviços" que uma página oferece, em vez de expor os detalhes e a mecânica da página. Como exemplo, pense na caixa de entrada de qualquer sistema de email baseado na web. Entre os serviços que oferece estão a capacidade de compor um novo e-mail, escolher ler um único e-mail e listar as linhas de assunto dos e-mails na caixa de entrada. Como esses são implementados não deve importar para o teste.
372+
Page Objects 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.
318373

319-
Porque estamos encorajando o desenvolvedor de um teste a tentar pensar sobre os serviços com os quais estão interagindo em vez da implementação, os Page Objects raramente devem expor a instância subjacente do WebDriver. Para facilitar isso, os métodos no Page Object devem retornar outros Page Objects. Isso significa que podemos efetivamente modelar a jornada do usuário em nosso aplicativo. Também significa que se a maneira como as páginas se relacionam entre si mudar (como quando a página de login pede ao usuário para alterar sua senha na primeira vez que eles entram em um serviço quando antes não fazia isso), simplesmente mudando a assinatura do método apropriado fará com que os testes falhem em compilação. Colocando de outra forma; podemos dizer quais testes falhariam sem precisar executá-los quando mudamos a relação entre as páginas e refletimos isso nos PageObjects.
374+
Because we're encouraging the developer of a test to try and think about the services they're interacting with rather than the implementation, Page Objects should seldom expose the underlying WebDriver instance. To facilitate this, **methods on the Page Object may return another Page Object, another Page Component Object, or even itself (this)**. 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 Page Objects.
320375

321-
Uma consequência dessa abordagem é que pode ser necessário modelar (por exemplo) tanto um login bem-sucedido quanto um mal-sucedido; ou um clique poderia ter um resultado diferente dependendo do estado do aplicativo. Quando isso acontece, é comum ter vários métodos no PageObject:
376+
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 Page Object:
322377

323378
```java
324379
public class LoginPage {
325380
public HomePage loginAs(String username, String password) {
326-
// ... mágica inteligente acontece aqui
381+
// ... clever magic happens here
327382
}
328383

329384
public LoginPage loginAsExpectingError(String username, String password) {
330-
// ... falha no login aqui, talvez porque o nome de usuário e/ou a senha estão incorretos
385+
// ... failed login here, maybe because one or both of the username and password are wrong
331386
}
332387

333388
public String getErrorMessage() {
334-
// Para que possamos verificar se o erro correto é mostrado
389+
// So we can verify that the correct error is shown
335390
}
336391
}
337392
```
338393

339-
O código apresentado acima mostra um ponto importante: os testes, não os Page Objects, devem ser responsáveis por fazer asserções sobre o estado de uma página. Por exemplo:
394+
The code presented above shows an important point: the tests, not the Page Objects, should be responsible for making assertions about the state of a page. For example:
340395

341396
```java
342397
public void testMessagesAreReadOrUnread() {
@@ -356,18 +411,18 @@ public void testMessagesAreReadOrUnread() {
356411
}
357412
```
358413

359-
Claro, como em toda diretriz, existem exceções, e uma que é comumente vista com Page Objects é verificar se o WebDriver está na página correta quando instanciamos o Page Object. Isso é feito no exemplo abaixo.
414+
Of course, as with every guideline, there are exceptions, and one that is commonly seen with Page Objects is to check that the WebDriver is on the correct page when we instantiate the Page Object. This is done in the example below.
360415

361-
Finalmente, um Page Object não precisa representar uma página inteira. Pode representar uma seção que aparece com frequência dentro de um site ou página, como a navegação do site. O princípio essencial é que há apenas um lugar em sua suíte de testes com conhecimento da estrutura do HTML de uma determinada (parte de uma) página.
416+
Finally, a Page Object need not represent an entire page and can be composed of Page Object Components. These components 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.
362417

363-
## Resumo
418+
## Summary
364419

365-
* Os métodos públicos representam os serviços que a página oferece
366-
* Tente não expor as entranhas da página
367-
* Geralmente não faça asserções
368-
* Métodos retornam outros PageObjects
369-
*Não precisa representar uma página inteira
370-
* Resultados diferentes para a mesma ação são modelados como métodos diferentes
420+
* The public methods represent the services that the page or component offers
421+
* Try not to expose the internals of the page or component
422+
* Generally don't make assertions
423+
* Methods return other Page Objects, Page Component Objects, or optionally themselves (for fluent syntax)
424+
* Need not represent an entire page all the time
425+
* Different results for the same action are modelled as different methods
371426

372427
## Example
373428

@@ -378,62 +433,63 @@ public class LoginPage {
378433
public LoginPage(WebDriver driver) {
379434
this.driver = driver;
380435

381-
// Verifica se estamos na página correta.
436+
// Check that we're on the right page.
382437
if (!"Login".equals(driver.getTitle())) {
383-
// Alternativamente, poderíamos navegar para a página de login, talvez fazendo logout primeiro
438+
// Alternatively, we could navigate to the login page, perhaps logging out first
384439
throw new IllegalStateException("This is not the login page");
385440
}
386441
}
387442

388-
// A página de login contém vários elementos HTML que serão representados como WebElements.
389-
// Os localizadores para esses elementos devem ser definidos apenas uma vez.
443+
// The login page contains several HTML elements that will be represented as WebElements.
444+
// The locators for these elements should only be defined once.
390445
By usernameLocator = By.id("username");
391446
By passwordLocator = By.id("passwd");
392447
By loginButtonLocator = By.id("login");
393448

394-
// A página de login permite que o usuário digite seu nome de usuário no campo de nome de usuário
449+
// The login page allows the user to type their username into the username field
395450
public LoginPage typeUsername(String username) {
396-
// Este é o único lugar que "sabe" como entrar com um nome de usuário
451+
// This is the only place that "knows" how to enter a username
397452
driver.findElement(usernameLocator).sendKeys(username);
398453

399-
// Retorna o objeto de página atual, já que esta ação não navega para uma página representada por outro Page Object
454+
// Return the current page object as this action doesn't navigate to a page represented by another PageObject
400455
return this;
401456
}
402-
Este é o único lugar que "sabe" como entrar com uma senha
403-
// A página de login permite que o usuário digite sua senha no campo de senha
457+
458+
// The login page allows the user to type their password into the password field
404459
public LoginPage typePassword(String password) {
405-
// Este é o único lugar que "sabe" como entrar com uma senha
460+
// This is the only place that "knows" how to enter a password
406461
driver.findElement(passwordLocator).sendKeys(password);
407462

408-
// Retorna o objeto de página atual, já que esta ação não navega para uma página representada por outro Page Object
463+
// Return the current page object as this action doesn't navigate to a page represented by another PageObject
409464
return this;
410465
}
411466

412-
// A página de login permite que o usuário envie o formulário de login
467+
// The login page allows the user to submit the login form
413468
public HomePage submitLogin() {
414-
// Este é o único lugar que envia o formulário de login e espera que o destino seja a página inicial.
415-
// Um método separado deve ser criado para a instância de clicar em login enquanto espera uma falha de login.
469+
// This is the only place that submits the login form and expects the destination to be the home page.
470+
// A seperate method should be created for the instance of clicking login whilst expecting a login failure.
416471
driver.findElement(loginButtonLocator).submit();
417472

418-
// Retorna um novo objeto de página representando o destino. Caso a página de login vá para algum outro lugar (por exemplo, um aviso legal),
419-
// então a alteração da assinatura do método para este método significará que todos os testes que dependem deste comportamento não serão compilados.
473+
// Return a new page object representing the destination. Should the login page ever
474+
// go somewhere else (for example, a legal disclaimer) then changing the method signature
475+
// for this method will mean that all tests that rely on this behaviour won't compile.
420476
return new HomePage(driver);
421477
}
422478

423-
// A página de login permite que o usuário envie o formulário de login sabendo que um nome de usuário inválido e/ou senha foram inseridos
479+
// The login page allows the user to submit the login form knowing that an invalid username and / or password were entered
424480
public LoginPage submitLoginExpectingFailure() {
425-
// Este é o único lugar que envia o formulário de login e espera que o destino seja a página de login devido à falha no login.
481+
// This is the only place that submits the login form and expects the destination to be the login page due to login failure.
426482
driver.findElement(loginButtonLocator).submit();
427483

428-
// Retorna um novo objeto de página representando o destino. Caso o usuário seja navegado para a página inicial depois de enviar um login com credenciais
429-
// que se espera falhar no login, o script falhará quando tentar instanciar o PageObject LoginPage.
484+
// Return a new page object representing the destination. Should the user ever be navigated to the home page after submiting a login with credentials
485+
// expected to fail login, the script will fail when it attempts to instantiate the LoginPage PageObject.
430486
return new LoginPage(driver);
431487
}
432488

433-
// Conceitualmente, a página de login oferece ao usuário o serviço de ser capaz de "entrar"
434-
// no aplicativo usando um nome de usuário e senha.
489+
// Conceptually, the login page offers the user the service of being able to "log into"
490+
// the application using a user name and password.
435491
public HomePage loginAs(String username, String password) {
436-
// Os métodos PageObject que inserem nome de usuário, senha e enviam login já foram definidos e não devem ser repetidos aqui.
492+
// The PageObject methods that enter username, password & submit login have already defined and should not be repeated here.
437493
typeUsername(username);
438494
typePassword(password);
439495
return submitLogin();

‎website_and_docs/content/documentation/test_practices/encouraged/page_object_models.zh-cn.md

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ A Page Object only models these as objects within the test code.
1919
This reduces the amount of duplicated code and means that if the UI changes,
2020
the fix needs only to be applied in one place.
2121

22-
Page Object is a Design Pattern that has become popular in test automation for
22+
Page Object Model is a Design Pattern that has become popular in test automation for
2323
enhancing test maintenance and reducing code duplication. A page object is an
2424
object-oriented class that serves as an interface to a page of your AUT. The
2525
tests then use the methods of this page object class whenever they need to
@@ -44,6 +44,7 @@ helpful tips beyond the scope of this user guide. To get you started,
4444
we’ll illustrate page objects with a simple example.
4545

4646
### Examples
47+
4748
First, consider an example, typical of test automation, that does not use a
4849
page object:
4950

@@ -75,7 +76,7 @@ must change.
7576
* The ID-locators would be spread in multiple tests, in all tests that had to
7677
use this login page.
7778

78-
Applying the page object techniques, this example could be rewritten like this
79+
Applying the page object model, this example could be rewritten like this
7980
in the following example of a page object for a Sign-in page.
8081

8182
```java
@@ -184,6 +185,7 @@ there are a few basic rules for getting the desired maintainability of your
184185
test code.
185186

186187
## Assertions in Page Objects
188+
187189
Page objects themselves should never make verifications or assertions. This is
188190
part of your test and should always be within the test’s code, never in a page
189191
object. The page object will contain the representation of the page, and the
@@ -198,6 +200,7 @@ HomePage constructors check that the expected page is available and ready for
198200
requests from the test.
199201

200202
## Page Component Objects
203+
201204
A page object does not necessarily need to represent all the parts of a
202205
page itself. This was [noted by Martin Fowler](https://martinfowler.com/bliki/PageObject.html#footnote-panel-object) in the early days, while first coining the term "panel objects".
203206

@@ -280,7 +283,7 @@ public class ProductsPage extends BasePage {
280283
.stream()
281284
.filter(condition) // Filter by product name or price
282285
.findFirst()
283-
.orElseThrow();
286+
.orElseThrow(() -> new RuntimeException("Product not found")); // Error thrown during actual test run
284287
}
285288
}
286289
```
@@ -348,7 +351,7 @@ public class ProductsTest {
348351
}
349352
```
350353

351-
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.
354+
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 as is the core principle of object-oriented programming. When applications are built, they are not made of a massive page entity. They are built with components contained in a page. Page Component Objects implement the same approach.
352355

353356
You can even
354357
nest component objects inside other component objects for more complex
@@ -357,6 +360,7 @@ components used throughout the site (e.g. a navigation bar), then it
357360
may improve maintainability and reduce code duplication.
358361

359362
## Other Design Patterns Used in Testing
363+
360364
There are other design patterns that also may be used in testing. Discussing all of these is
361365
beyond the scope of this user guide. Here, we merely want to introduce the
362366
concepts to make the reader aware of some of the things that can be done. As
@@ -365,12 +369,11 @@ reader to search for blogs on these topics.
365369

366370
## Implementation Notes
367371

372+
Page Objects 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.
368373

369-
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.
370-
371-
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.
374+
Because we're encouraging the developer of a test to try and think about the services they're interacting with rather than the implementation, Page Objects should seldom expose the underlying WebDriver instance. To facilitate this, **methods on the Page Object may return another Page Object, another Page Component Object, or even itself (this)**. 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 Page Objects.
372375

373-
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:
376+
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 Page Object:
374377

375378
```java
376379
public class LoginPage {
@@ -388,7 +391,7 @@ public class LoginPage {
388391
}
389392
```
390393

391-
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:
394+
The code presented above shows an important point: the tests, not the Page Objects, should be responsible for making assertions about the state of a page. For example:
392395

393396
```java
394397
public void testMessagesAreReadOrUnread() {
@@ -408,17 +411,17 @@ public void testMessagesAreReadOrUnread() {
408411
}
409412
```
410413

411-
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.
414+
Of course, as with every guideline, there are exceptions, and one that is commonly seen with Page Objects is to check that the WebDriver is on the correct page when we instantiate the Page Object. This is done in the example below.
412415

413-
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.
416+
Finally, a Page Object need not represent an entire page and can be composed of Page Object Components. These components 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.
414417

415418
## Summary
416419

417-
* The public methods represent the services that the page offers
418-
* Try not to expose the internals of the page
420+
* The public methods represent the services that the page or component offers
421+
* Try not to expose the internals of the page or component
419422
* Generally don't make assertions
420-
* Methods return other PageObjects
421-
* Need not represent an entire page
423+
* Methods return other Page Objects, Page Component Objects, or optionally themselves (for fluent syntax)
424+
* Need not represent an entire page all the time
422425
* Different results for the same action are modelled as different methods
423426

424427
## Example
@@ -492,4 +495,4 @@ public class LoginPage {
492495
return submitLogin();
493496
}
494497
}
495-
```
498+
```

0 commit comments

Comments
 (0)
Please sign in to comment.