Course contentsShow
← Java
Lesson 2532 of 2,87047. Java Platform Module System (JPMS)Free lesson

Testing Modular Code with Non-Modular Test Frameworks

Configure your build to allow test frameworks like JUnit to access module internals using opens directives.

Testing Modular Code with Non-Modular Test Frameworks

What You'll Learn

You'll learn how to configure your modular application so that testing frameworks like JUnit can access your module's internal packages during test execution.

The Testing Challenge with Modules

When you modularize your code, strong encapsulation becomes the default—only exported packages are accessible. But test frameworks like JUnit need to instantiate your test classes, call private methods via reflection, and access package-private classes. These frameworks often haven't been fully modularized themselves, creating a friction point.

Think of it like this: your module is a locked building with only certain public entrances (exported packages). Your tests live in the same building but need backstage access to all rooms, not just the lobby.

Using opens in Your Module Descriptor

The solution is to open your packages specifically for testing. In your module-info.java, you use qualified opens directives to grant reflective access to test frameworks:

module com.example.myapp {
    requires java.base;
    exports com.example.myapp.api;
    
    // Open internal packages to test frameworks
    opens com.example.myapp.internal to org.junit.platform.commons;
    opens com.example.myapp.service to org.junit.platform.commons;
}

This tells the module system: "Allow org.junit.platform.commons (the JUnit module handling reflection) to access everything in these packages, even non-public types and members."

Build Tool Configuration

Modern build tools handle this gracefully. Maven Surefire and Gradle automatically add necessary --add-opens flags during test execution, but you may need to explicitly list which modules your tests require in a test-specific module-info.java or through build configuration.

Key Takeaway: Use qualified opens directives in your module descriptor to grant test frameworks reflective access to internal packages, enabling non-modular testing tools to work seamlessly with your modular code.