A good test does not have any objects created in it.
This is not a good test:
@Test
public void canFilterByBooksTest() {
HomePage homePage = new HomePage(driver);
homePage.open();
Verify.verify(homePage.isDisplayed(), "home page is not displayed!");
homePage.searchBy(KEYWORD);
ResultsPage resultsPage = new ResultsPage(driver);
Verify.verify(resultsPage.isDisplayed(), "results page is not displayed!");
}
What is not good about it?
The test creates 2 objects.
First, the homePage object:
HomePage homePage = new HomePage(driver);
Second, the resultsPage object:
ResultsPage resultsPage = new ResultsPage(driver);
What is the big deal about creating these objects?
A test that creates objects is not clear for people that do not have programming knowledge.
How do you explain the following line of code to someone who does not know Java?
ResultsPage resultsPage = new ResultsPage(driver);
How can we remove these 2 lines of code?
It is easy to get rid of creating the resultsPage object.
We need to replace
homePage.searchBy(KEYWORD);
ResultsPage resultsPage = new ResultsPage(driver);
with
ResultsPage resultsPage = homePage.searchBy(KEYWORD);
This can be accomplished by changing the searchBy() method so that it returns a ResultsPage object.
What about the homePage object?
We can create a test class helper method that opens home page and returns a HomePage object:
private HomePage openHomePage() {
HomePage homePage = new HomePage(driver);
homePage.open();
return homePage;
}
With these changes, the test is much more clear, not only for us, but also for people that do not know any JAVA:
@Test
public void canFilterByBooksTest2() {
HomePage homePage = openHomePage();
Verify.verify(homePage.isDisplayed(), "home page is not displayed!");
ResultsPage resultsPage = homePage.searchBy(KEYWORD);
Verify.verify(resultsPage.isDisplayed(), "results page is not displayed!");
}
In conclusion, avoid creating objects in the test method.
This makes the tests more clear for everyone.