Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Part 9: Reducing duplication with app objects

In automated testing we often use app objects to abstract code. This reduces duplication of code and locators. If we need to change a common section of code we can change it only in a single app object, rather than having to change it in 10 or 20 test files. This article provides the basics of how to use app objects.

App objects: getting started

The app object is a Python class containing methods and properties that represent actions on the page. Let's look at how we might use these in a theoretical example.

homepage.py

Here is a frame we might use for the Homepage app with some pseudo-code included.

class Homepage:
        __init__(self, marionette):
                # Marionette is passed in so that the object can use it
                self.marionette = marionette
 
        def switch_to_homepage_frame(self):
                # Code for switching to System then to Homepage frame

        def tap_contacts_icon(self):
                # Code to tap the icon
                # Switch to Contacts frame
                # Now we return the Contacts app object as it has focus
                from contacts import Contacts
                return Contacts(self.marionette)

contacts.py

And here's what we might use for the Contacts app, again with some pseudo-code.

class Contacts:
        _new_contact_button = (By.ID, ‘id’)
 
        def tap_new_contact(self):
                # Tap new contact icon
                # Wait for event
 
        def type_given_name(self, name_string):
                # element.send_keys(name_string)

test_contacts.py

To understand how this works in the context of a test, here is a quick sample that makes use of the Homepage class:

from homepage import Homepage

def test_add_contact(self):
        homepage = Homepage(self.marionette)
        homepage.switch_to_homepage_frame()
         
contacts = homepage.tap_contacts_icon()
contacts.tap_new_contact()

Updating your tests

From here we'd like to challenge you to update all of your test files to use the new app objects system.

This is a difficult task and if you’re not familiar with Python class structures you may need to consult some books for references and code samples.

When you have finished ideally you will have a clear separation between test files:

  1. TestBase will contain the setUp() and tearDown() methods
  2. The app objects will contain page interactions and locators
  3. Your test files will contain just the test steps.

Good luck!

Document Tags and Contributors

 Contributors to this page: chrisdavidmills, zac_c
 Last updated by: chrisdavidmills,