You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: website_and_docs/content/documentation/test_practices/encouraged/page_object_models.ja.md
+19-16Lines changed: 19 additions & 16 deletions
Original file line number
Diff line number
Diff line change
@@ -19,7 +19,7 @@ A Page Object only models these as objects within the test code.
19
19
This reduces the amount of duplicated code and means that if the UI changes,
20
20
the fix needs only to be applied in one place.
21
21
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
23
23
enhancing test maintenance and reducing code duplication. A page object is an
24
24
object-oriented class that serves as an interface to a page of your AUT. The
25
25
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,
44
44
we’ll illustrate page objects with a simple example.
45
45
46
46
### Examples
47
+
47
48
First, consider an example, typical of test automation, that does not use a
48
49
page object:
49
50
@@ -75,7 +76,7 @@ must change.
75
76
* The ID-locators would be spread in multiple tests, in all tests that had to
76
77
use this login page.
77
78
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
79
80
in the following example of a page object for a Sign-in page.
80
81
81
82
```java
@@ -184,6 +185,7 @@ there are a few basic rules for getting the desired maintainability of your
184
185
test code.
185
186
186
187
## Assertions in Page Objects
188
+
187
189
Page objects themselves should never make verifications or assertions. This is
188
190
part of your test and should always be within the test’s code, never in a page
189
191
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
198
200
requests from the test.
199
201
200
202
## Page Component Objects
203
+
201
204
A page object does not necessarily need to represent all the parts of a
202
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".
203
206
@@ -280,7 +283,7 @@ public class ProductsPage extends BasePage {
280
283
.stream()
281
284
.filter(condition) // Filter by product name or price
282
285
.findFirst()
283
-
.orElseThrow();
286
+
.orElseThrow(() ->newRuntimeException("Product not found")); // Error thrown during actual test run
284
287
}
285
288
}
286
289
```
@@ -348,7 +351,7 @@ public class ProductsTest {
348
351
}
349
352
```
350
353
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.
352
355
353
356
You can even
354
357
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
357
360
may improve maintainability and reduce code duplication.
358
361
359
362
## Other Design Patterns Used in Testing
363
+
360
364
There are other design patterns that also may be used in testing. Discussing all of these is
361
365
beyond the scope of this user guide. Here, we merely want to introduce the
362
366
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.
365
369
366
370
## Implementation Notes
367
371
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.
368
373
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.
372
375
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:
374
377
375
378
```java
376
379
publicclassLoginPage {
@@ -388,7 +391,7 @@ public class LoginPage {
388
391
}
389
392
```
390
393
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:
392
395
393
396
```java
394
397
publicvoid testMessagesAreReadOrUnread() {
@@ -408,17 +411,17 @@ public void testMessagesAreReadOrUnread() {
408
411
}
409
412
```
410
413
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.
412
415
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.
414
417
415
418
## Summary
416
419
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
419
422
* 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
422
425
* Different results for the same action are modelled as different methods
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.
18
21
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.
20
30
21
-
### Vantagens
31
+
### Advantages
22
32
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.
25
37
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.
27
45
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
* 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.
54
78
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.
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.
99
124
100
125
```java
101
126
importorg.openqa.selenium.By;
102
127
importorg.openqa.selenium.WebDriver;
103
128
104
129
/**
105
-
* Page Object encapsula a Página Inicial
130
+
* Page Object encapsulates the Home Page
106
131
*/
107
132
publicclassHomePage {
108
133
protectedWebDriver driver;
@@ -119,27 +144,29 @@ public class HomePage {
119
144
}
120
145
121
146
/**
122
-
* Obtém a mensagem (tag h1)
147
+
* Get message (h1 tag)
123
148
*
124
-
* @return String da mensagem de texto
149
+
* @return String message text
125
150
*/
126
151
publicStringgetMessageText() {
127
152
return driver.findElement(messageBy).getText();
128
153
}
129
154
130
155
publicHomePagemanageProfile() {
131
-
//Encapsulamento da página para gerenciar a funcionalidade do perfil
156
+
//Page encapsulation to manage profile functionality
132
157
returnnewHomePage(driver);
133
158
}
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 */
135
162
}
136
163
```
137
164
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.
139
166
140
167
```java
141
168
/***
142
-
* Testes da funcionalidade de login
169
+
* Tests login feature
143
170
*/
144
171
publicclassTestLogin {
145
172
@@ -153,22 +180,40 @@ public class TestLogin {
153
180
}
154
181
```
155
182
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.
157
194
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.
160
201
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
162
203
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".
165
206
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.
167
212
168
-
Por exemplo, uma página de Produtos tem vários produtos.
213
+
For example, a Products page has multiple products.
169
214
170
215
```html
171
-
<!--Página de Produtos-->
216
+
<!--Products Page-->
172
217
<divclass="header_container">
173
218
<spanclass="title">Products</span>
174
219
</div>
@@ -189,7 +234,8 @@ Por exemplo, uma página de Produtos tem vários produtos.
189
234
</div>
190
235
```
191
236
192
-
Cada produto é um componente da página de Produtos.
237
+
Each product is a component of the Products page.
238
+
193
239
194
240
```html
195
241
<!-- Inventory Item -->
@@ -202,7 +248,7 @@ Cada produto é um componente da página de Produtos.
202
248
</div>
203
249
```
204
250
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.
206
252
207
253
```java
208
254
publicabstractclassBasePage {
@@ -217,32 +263,32 @@ public abstract class BasePage {
217
263
publicclassProductsPageextendsBasePage {
218
264
publicProductsPage(WebDriverdriver) {
219
265
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
).setScale(2, RoundingMode.UNNECESSARY); //Higienização e formatação
319
+
).setScale(2, RoundingMode.UNNECESSARY); //Sanitation and formatting
274
320
}
275
321
276
322
publicvoidaddToCart() {
@@ -279,23 +325,23 @@ public class Product extends BaseComponent {
279
325
}
280
326
```
281
327
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.
283
329
284
330
```java
285
331
publicclassProductsTest {
286
332
@Test
287
333
publicvoidtestProductInventory() {
288
334
var productsPage =newProductsPage(driver); // page object
289
335
var products = productsPage.getProducts();
290
-
assertEquals(6, products.size()); //esperado, atual
336
+
assertEquals(6, products.size()); //expected, actual
291
337
}
292
338
293
339
@Test
294
340
publicvoidtestProductPrices() {
295
341
var productsPage =newProductsPage(driver);
296
342
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
299
345
var backpack = productsPage.getProduct(p -> p.getName().equals("Backpack")); // page component object
300
346
var bikeLight = productsPage.getProduct(p -> p.getName().equals("Bike Light"));
301
347
@@ -305,38 +351,47 @@ public class ProductsTest {
305
351
}
306
352
```
307
353
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.
309
361
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
311
363
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.
314
369
315
-
## Notas de Implementação
370
+
## Implementation Notes
316
371
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.
318
373
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.
320
375
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:
// ... 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
331
386
}
332
387
333
388
publicStringgetErrorMessage() {
334
-
//Para que possamos verificar se o erro correto é mostrado
389
+
//So we can verify that the correct error is shown
335
390
}
336
391
}
337
392
```
338
393
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:
340
395
341
396
```java
342
397
publicvoid testMessagesAreReadOrUnread() {
@@ -356,18 +411,18 @@ public void testMessagesAreReadOrUnread() {
356
411
}
357
412
```
358
413
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.
360
415
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.
362
417
363
-
## Resumo
418
+
## Summary
364
419
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
371
426
372
427
## Example
373
428
@@ -378,62 +433,63 @@ public class LoginPage {
378
433
publicLoginPage(WebDriverdriver) {
379
434
this.driver = driver;
380
435
381
-
//Verifica se estamos na página correta.
436
+
//Check that we're on the right page.
382
437
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
384
439
thrownewIllegalStateException("This is not the login page");
385
440
}
386
441
}
387
442
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.
390
445
By usernameLocator =By.id("username");
391
446
By passwordLocator =By.id("passwd");
392
447
By loginButtonLocator =By.id("login");
393
448
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
395
450
publicLoginPagetypeUsername(Stringusername) {
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
//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
409
464
returnthis;
410
465
}
411
466
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
413
468
publicHomePagesubmitLogin() {
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.
416
471
driver.findElement(loginButtonLocator).submit();
417
472
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.
420
476
returnnewHomePage(driver);
421
477
}
422
478
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
424
480
publicLoginPagesubmitLoginExpectingFailure() {
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.
426
482
driver.findElement(loginButtonLocator).submit();
427
483
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.
430
486
returnnewLoginPage(driver);
431
487
}
432
488
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"
Copy file name to clipboardExpand all lines: website_and_docs/content/documentation/test_practices/encouraged/page_object_models.zh-cn.md
+19-16Lines changed: 19 additions & 16 deletions
Original file line number
Diff line number
Diff line change
@@ -19,7 +19,7 @@ A Page Object only models these as objects within the test code.
19
19
This reduces the amount of duplicated code and means that if the UI changes,
20
20
the fix needs only to be applied in one place.
21
21
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
23
23
enhancing test maintenance and reducing code duplication. A page object is an
24
24
object-oriented class that serves as an interface to a page of your AUT. The
25
25
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,
44
44
we’ll illustrate page objects with a simple example.
45
45
46
46
### Examples
47
+
47
48
First, consider an example, typical of test automation, that does not use a
48
49
page object:
49
50
@@ -75,7 +76,7 @@ must change.
75
76
* The ID-locators would be spread in multiple tests, in all tests that had to
76
77
use this login page.
77
78
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
79
80
in the following example of a page object for a Sign-in page.
80
81
81
82
```java
@@ -184,6 +185,7 @@ there are a few basic rules for getting the desired maintainability of your
184
185
test code.
185
186
186
187
## Assertions in Page Objects
188
+
187
189
Page objects themselves should never make verifications or assertions. This is
188
190
part of your test and should always be within the test’s code, never in a page
189
191
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
198
200
requests from the test.
199
201
200
202
## Page Component Objects
203
+
201
204
A page object does not necessarily need to represent all the parts of a
202
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".
203
206
@@ -280,7 +283,7 @@ public class ProductsPage extends BasePage {
280
283
.stream()
281
284
.filter(condition) // Filter by product name or price
282
285
.findFirst()
283
-
.orElseThrow();
286
+
.orElseThrow(() ->newRuntimeException("Product not found")); // Error thrown during actual test run
284
287
}
285
288
}
286
289
```
@@ -348,7 +351,7 @@ public class ProductsTest {
348
351
}
349
352
```
350
353
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.
352
355
353
356
You can even
354
357
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
357
360
may improve maintainability and reduce code duplication.
358
361
359
362
## Other Design Patterns Used in Testing
363
+
360
364
There are other design patterns that also may be used in testing. Discussing all of these is
361
365
beyond the scope of this user guide. Here, we merely want to introduce the
362
366
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.
365
369
366
370
## Implementation Notes
367
371
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.
368
373
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.
372
375
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:
374
377
375
378
```java
376
379
publicclassLoginPage {
@@ -388,7 +391,7 @@ public class LoginPage {
388
391
}
389
392
```
390
393
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:
392
395
393
396
```java
394
397
publicvoid testMessagesAreReadOrUnread() {
@@ -408,17 +411,17 @@ public void testMessagesAreReadOrUnread() {
408
411
}
409
412
```
410
413
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.
412
415
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.
414
417
415
418
## Summary
416
419
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
419
422
* 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
422
425
* Different results for the same action are modelled as different methods
0 commit comments