Search code examples
javamavenoopproject-structure

Best way of reusing Java classes across different projects?


I am currently writing Selenium WebDriver tests for a variety of websites each using the same proprietary framework.

Because of this, there are many test cases that can be quite similar across different websites. As such I have made my test classes as generic as possible and made it so that every XPath/CSS Selector/ID used to locate elements is defined in a Constants class, which is unique to every project.

But, in some cases, the code for the same test can be the same across different websites, since I wrote them generically. In addition each test is a direct/indirect extension of a BasicTest class which contains code that is likely to be reused by different tests (ex: WebDriver instance declaration, etc)

The way I thought about setting my test structure was the following:

  • one generic project that is "reused" by each subsequent project;
  • one project per website with its own definition of the Constantsclass and a TestSuite class that it can use to run both generic tests and tests specific to itself.

This would allow me not to have copies of these generic tests in each of my test projects.

The problem is that I don't really know how to set this up. The GenericProject is going to contain tests that require variables from Constant, but it makes no sense to have generic Constants. Plus, will I be able to call those tests inside my website project-specific TestSuites? If I redefine Constants in each specific project, will those constants be used for the generic tests defined in GenericProject? How can I even set it up so that I can reuse Project A's classes inside of Project B, C, D... etc?


Solution

    • Extract your constants to a properties file which exists in each module as src/test/resources/common.properties.
    • Use org.apache.commons:commons-configuration2 PropertiesConfiguration to read this file. It will handle nested properties just fine.
    • Common code can be shared by depending on your GenericModule. Official instructions for two models of doing this (extract common tests to a new module or use a test-jar) are here