0
0
JUnittesting~8 mins

TestInstance lifecycle per class in JUnit - Framework Patterns

Choose your learning style9 modes available
Framework Mode - TestInstance lifecycle per class
Folder Structure
src/
└── test/
    └── java/
        └── com/
            └── example/
                ├── tests/
                │   └── CalculatorTest.java
                ├── pages/
                │   └── CalculatorPage.java
                ├── utils/
                │   └── TestUtils.java
                └── config/
                    └── TestConfig.java
Test Framework Layers
  • Test Classes: Contain test methods annotated with @Test. Use @TestInstance(TestInstance.Lifecycle.PER_CLASS) to create one test instance per class.
  • Page Objects: Encapsulate UI elements and actions for reusability and maintainability.
  • Utilities: Helper methods for common tasks like waits, data generation, or assertions.
  • Configuration: Manage environment settings, credentials, and test parameters.
  • Test Runner: JUnit platform runs tests and manages lifecycle annotations.
Configuration Patterns
  • Environment Profiles: Use src/test/resources to store application.properties or YAML files for different environments (dev, test, prod).
  • System Properties: Pass parameters like browser type or environment via JVM arguments (-Dbrowser=chrome).
  • Credentials Management: Store sensitive data securely outside source code, e.g., environment variables or encrypted files.
  • JUnit Lifecycle Annotations: Use @BeforeAll and @AfterAll with @TestInstance(TestInstance.Lifecycle.PER_CLASS) to run setup/teardown once per class instance.
Test Reporting and CI/CD Integration
  • JUnit Reports: Generate XML reports automatically after test runs for CI tools.
  • Build Tools: Use Maven or Gradle to run tests and produce reports.
  • CI/CD Pipelines: Integrate tests in Jenkins, GitHub Actions, or GitLab CI to run on code commits.
  • Test Instance Lifecycle Impact: Using PER_CLASS lifecycle allows @BeforeAll and @AfterAll methods to be non-static, simplifying resource management.
Best Practices
  1. Use @TestInstance(TestInstance.Lifecycle.PER_CLASS) to share state: When tests need to share expensive setup or state, this lifecycle creates one instance per class.
  2. Keep tests independent: Avoid sharing mutable state that can cause flaky tests.
  3. Use non-static @BeforeAll/@AfterAll: With PER_CLASS, these methods can be instance methods, improving readability.
  4. Clean up resources properly: Use @AfterAll to release resources initialized in @BeforeAll.
  5. Document lifecycle choice: Explain why PER_CLASS is used to help future maintainers.
Self Check

Where in this folder structure would you add a new test class that uses @TestInstance(TestInstance.Lifecycle.PER_CLASS) to test the login functionality?

Key Result
JUnit test classes use @TestInstance(TestInstance.Lifecycle.PER_CLASS) to create one test instance per class, enabling non-static lifecycle methods and shared setup.