Object model example java

Page Object Model with JAVA

Page Object Model is one of the most used test automation framework pattern and in this tutorial I will explain you this test automation design pattern. Before, Ege Aksöz also wrote an article on POM with C# . You can also see the definition of POM and the main advantages. Thus, I do not go into fundamentals again. I just want to show you a real-life basic POM example with JAVA.

Our POM framework generally consists of 3 basic abstraction layer. These are tests, pages, and util. Complicated frameworks comprise more abstraction layers. We start from the basics so we will have three abstraction layers. In this article, I will not write any class in Util layer but we will improve our POM framework in later articles and I will add new utility classes to this layer.

Tests: It comprises of our test classes.

Pages: It comprises of page classes.

Util: It comprises of utility and helper classes.

I will select one of the most popular Turkish e-commerce site n11.com as a test website and we will implement basic failed login scenarios with POM & JAVA & TestNG. Let’s Start!

At the end of the project, our project structure will be like this.

It is always better to start with requirements, features, or in other terms our tests. It is like a top-down approach and this approach helps you not to make too many mistakes during creating your test automation framework. Thus, first I will start to create our LoginTest class. Our login scenarios are as follows:

  • InvalidUsernameInvalidPassword()
    • Given I am at Home Page
    • When I go to Login Page
    • And I try to login the website with invalid username and password
    • Then I see valid error messages
    • EmptyUsernameEmptPassword()
      • Given I am at Home Page
      • When I go to Login Page
      • And I try to login the website with empty username and password
      • Then I see valid error messages
      1. We need to instantiate the required Page classes
      2. Use the appropriate page methods
      3. Do the assertions

      Here is the loginTests.java class:

      package tests; import org.testng.annotations.Test; import pages.HomePage; import pages.LoginPage; public class LoginTests extends BaseTest < @Test (priority = 0) public void invalidLoginTest_InvalidUserNameInvalidPassword () < //*************PAGE INSTANTIATIONS************* HomePage homePage = new HomePage(driver); //*************PAGE METHODS******************** homePage.goToN11() .goToLoginPage() .loginToN11("[email protected]", "11223344") .verifyLoginPassword(("E-posta adresiniz veya şifreniz hatalı")) .verifyLoginPassword(("E-posta adresiniz veya şifreniz hatalı")); > @Test (priority = 1) public void invalidLoginTest_EmptyUserEmptyPassword () < //*************PAGE INSTANTIATIONS************* HomePage homePage = new HomePage(driver); //*************PAGE METHODS******************** homePage.goToN11() .goToLoginPage() .loginToN11("","") .verifyLoginUserName("Lütfen e-posta adresinizi girin.") .verifyLoginPassword("Bu alanın doldurulması zorunludur."); >>

      We have a lot of reds line in this class, we need to start to resolve them until our project will not have any red lines and problems. Let’s start with the BaseTest class.

      BaseTest class contains all common functionalities and variables of test classes and all test classes extend this BaseTest class. This is one of the main features of Object Oriented Design (OOD) “Inheritance“. The code of BaseTest is shown below.

      package tests; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; public class BaseTest < public WebDriver driver; @BeforeClass public void setup () < //Create a Chrome driver. All test classes use this. driver = new ChromeDriver(); //Maximize Window driver.manage().window().maximize(); >@AfterClass public void teardown () < driver.quit(); >>

      In this class, we declared the driver variable. This is used by all test classes. Also, we wrote @BeforeClass setup method and @AfterClass teardown method. Again, all test classes use these methods.

      In the setup method, we create a ChromeDriver and maximize the browser.

      In the teardown method, I closed all the browsers with driver.quit(); code line.

      That’s all for the base test class.

      Now, let’s write the BasePage class. BasePage class contains the common methods of all page classes such as click, writeText, readText, assertEquals etc. Here is it’s code.

      package pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; public class BasePage < public WebDriver driver; public WebDriverWait wait; //Constructor public BasePage (WebDriver driver)< this.driver = driver; wait = new WebDriverWait(driver,15); >//Wait Wrapper Method public void waitVisibility(By elementBy) < wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(elementBy)); >//Click Method public void click (By elementBy) < waitVisibility(elementBy); driver.findElement(elementBy).click(); >//Write Text public void writeText (By elementBy, String text) < waitVisibility(elementBy); driver.findElement(elementBy).sendKeys(text); >//Read Text public String readText (By elementBy) < waitVisibility(elementBy); return driver.findElement(elementBy).getText(); >//Assert public void assertEquals (By elementBy, String expectedText) < waitVisibility(elementBy); Assert.assertEquals(readText(elementBy), expectedText); >>

      Now, we can create our page classes. The first one is HomePage.java class. In this class we will declare:

      We will have two methods, one of them opens the homepage and the other one opens the login page. Here is the code.

      package pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.WebDriverWait; import sun.rmi.runtime.Log; public class HomePage extends BasePage < //*********Constructor********* public HomePage (WebDriver driver) < super(driver); >//*********Page Variables********* String baseURL = "http://www.n11.com/"; //*********Web Elements********* By signInButtonBy = By.className("btnSignIn"); //*********Page Methods********* //Go to Homepage public HomePage goToN11 () < driver.get(baseURL); return this; >//Go to LoginPage public LoginPage goToLoginPage () < click(signInButtonBy); return new LoginPage(driver); >>

      Another page class in LoginPage.java class. We will have three methods. One of them does the login operation, the other ones are assertion methods. Checks the login messages as expected or not and set the test fail or pass. Here is the code of LoginPage.java class.

      package pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; public class LoginPage extends BasePage < //*********Constructor********* public LoginPage(WebDriver driver) < super(driver); >//*********Web Elements********* By usernameBy = By.id("email"); By passwordBy = By.id("password"); By loginButtonBy = By.id("loginButton"); By errorMessageUsernameBy = By.xpath("//*[@id=\"loginForm\"]/div[1]/div/div"); By errorMessagePasswordBy = By.xpath("//*[@id=\"loginForm\"]/div[2]/div/div "); //*********Page Methods********* public LoginPage loginToN11 (String username, String password) < //Enter Username(Email) writeText(usernameBy,username); //Enter Password writeText(passwordBy, password); //Click Login Button click(loginButtonBy); return this; >//Verify Username Condition public LoginPage verifyLoginUserName (String expectedText) < assertEquals(errorMessageUsernameBy, expectedText); return this; >//Verify Password Condition public LoginPage verifyLoginPassword (String expectedText) < assertEquals(errorMessagePasswordBy, expectedText); return this; >>

      Here are the pom.xml and TestNG.xml files.

        4.0.0 n11project n11project 1.0-SNAPSHOT  org.seleniumhq.selenium selenium-java 3.14.0 test  org.testng testng 6.14.3     org.apache.maven.plugins maven-compiler-plugin 1.8 1.8   org.apache.maven.plugins maven-surefire-plugin 2.19  TestNG.xml      

      When we run our project, we will get below test results 😉

      We can improve this POM framework with Utility classes such as DesiredcapabilitiesManager, AJAXWaiter, Assertions, Listeners, Reporters, PropertyReaders, and so on. We will see the improved version of this in the next articles. You can reach the source code of the project on swtestacademy POM JAVA Example Github Page .

      Selenium Webdriver Tutorial Series

      [fusion_widget_area name=”avada-custom-sidebar-seleniumwidget” title_size=”” title_color=”” background_color=”” padding_top=”” padding_right=”” padding_bottom=”” padding_left=”” hide_on_mobile=”small-visibility,medium-visibility,large-visibility” >

      Onur Baskirt is a Software Engineering Leader with international experience in world-class companies. Now, he is a Software Engineering Lead at Emirates Airlines in Dubai.

      Источник

      Object model example java

      This section describes four use cases of the object model API: creating an object model from JSON data, creating an object model from application code, navigating an object model, and writing an object model to a stream.

      The following topics are addressed here:

      Creating an Object Model from JSON Data

      The following code demonstrates how to create an object model from JSON data in a text file:

      import java.io.FileReader; import javax.json.Json; import javax.json.JsonReader; import javax.json.JsonStructure; . JsonReader reader = Json.createReader(new FileReader("jsondata.txt")); JsonStructure jsonst = reader.read();

      The object reference jsonst can be either of type JsonObject or of type JsonArray , depending on the contents of the file. JsonObject and JsonArray are subtypes of JsonStructure . This reference represents the top of the tree and can be used to navigate the tree or to write it to a stream as JSON data.

      Creating an Object Model from Application Code

      The following code demonstrates how to create an object model from application code:

      import javax.json.Json; import javax.json.JsonObject; . JsonObject model = Json.createObjectBuilder() .add("firstName", "Duke") .add("lastName", "Java") .add("age", 18) .add("streetAddress", "100 Internet Dr") .add("city", "JavaTown") .add("state", "JA") .add("postalCode", "12345") .add("phoneNumbers", Json.createArrayBuilder() .add(Json.createObjectBuilder() .add("type", "mobile") .add("number", "111-111-1111")) .add(Json.createObjectBuilder() .add("type", "home") .add("number", "222-222-2222"))) .build();

      The object reference model represents the top of the tree, which is created by nesting calls to the add methods and built by calling the build method. The JsonObjectBuilder class contains the following add methods:

      JsonObjectBuilder add(String name, BigDecimal value) JsonObjectBuilder add(String name, BigInteger value) JsonObjectBuilder add(String name, boolean value) JsonObjectBuilder add(String name, double value) JsonObjectBuilder add(String name, int value) JsonObjectBuilder add(String name, JsonArrayBuilder builder) JsonObjectBuilder add(String name, JsonObjectBuilder builder) JsonObjectBuilder add(String name, JsonValue value) JsonObjectBuilder add(String name, long value) JsonObjectBuilder add(String name, String value) JsonObjectBuilder addNull(String name)

      The JsonArrayBuilder class contains similar add methods that do not have a name (key) parameter. You can nest arrays and objects by passing a new JsonArrayBuilder object or a new JsonObjectBuilder object to the corresponding add method, as shown in this example.

      The resulting tree represents the JSON data from JSON Syntax.

      The following code demonstrates a simple approach to navigating an object model:

      import javax.json.JsonValue; import javax.json.JsonObject; import javax.json.JsonArray; import javax.json.JsonNumber; import javax.json.JsonString; . public static void navigateTree(JsonValue tree, String key) < if (key != null) System.out.print("Key " + key + ": "); switch(tree.getValueType()) < case OBJECT: System.out.println("OBJECT"); JsonObject object = (JsonObject) tree; for (String name : object.keySet()) navigateTree(object.get(name), name); break; case ARRAY: System.out.println("ARRAY"); JsonArray array = (JsonArray) tree; for (JsonValue val : array) navigateTree(val, null); break; case STRING: JsonString st = (JsonString) tree; System.out.println("STRING " + st.getString()); break; case NUMBER: JsonNumber num = (JsonNumber) tree; System.out.println("NUMBER " + num.toString()); break; case TRUE: case FALSE: case NULL: System.out.println(tree.getValueType().toString()); break; >>

      The method navigateTree can be used with the models built in Creating an Object Model from JSON Data and Creating an Object Model from Application Code as follows:

      The navigateTree method takes two arguments: a JSON element and a key. The key is used only to help print the key-value pairs inside objects. Elements in a tree are represented by the JsonValue type. If the element is an object or an array, a new call to this method is made for every element contained in the object or array. If the element is a value, it is printed to the standard output.

      The JsonValue.getValueType method identifies the element as an object, an array, or a value. For objects, the JsonObject.keySet method returns a set of strings that contains the keys in the object, and the JsonObject.get(String name) method returns the value of the element whose key is name . For arrays, JsonArray implements the List interface. You can use enhanced for loops with the Set instance returned by JsonObject.keySet and with instances of JsonArray , as shown in this example.

      The navigateTree method for the model built in Creating an Object Model from Application Code produces the following output:

      OBJECT Key firstName: STRING Duke Key lastName: STRING Java Key age: NUMBER 18 Key streetAddress: STRING 100 Internet Dr Key city: STRING JavaTown Key state: STRING JA Key postalCode: STRING 12345 Key phoneNumbers: ARRAY OBJECT Key type: STRING mobile Key number: STRING 111-111-1111 OBJECT Key type: STRING home Key number: STRING 222-222-2222

      Writing an Object Model to a Stream

      The object models created in Creating an Object Model from JSON Data and Creating an Object Model from Application Code can be written to a stream using the JsonWriter class as follows:

      import java.io.StringWriter; import javax.json.JsonWriter; . StringWriter stWriter = new StringWriter(); JsonWriter jsonWriter = Json.createWriter(stWriter); jsonWriter.writeObject(model); jsonWriter.close(); String jsonData = stWriter.toString(); System.out.println(jsonData);

      The Json.createWriter method takes an output stream as a parameter. The JsonWriter.writeObject method writes the object to the stream. The JsonWriter.close method closes the underlying output stream.

      The following example uses try -with-resources to close the JSON writer automatically:

      StringWriter stWriter = new StringWriter(); try (JsonWriter jsonWriter = Json.createWriter(stWriter)) < jsonWriter.writeObject(model); >String jsonData = stWriter.toString(); System.out.println(jsonData);

      Источник

      Читайте также:  Org apache commons logging logfactory java lang classnotfoundexception
Оцените статью