Bird
Raised Fist0
JUnittesting~15 mins

Package-level test organization in JUnit - Build an Automation Script

Choose your learning style10 modes available
Verify package-level test organization with JUnit
Preconditions (2)
Step 1: Run all tests in the package 'com.example.utils'
Step 2: Verify that all test classes in 'com.example.utils' package are executed
Step 3: Run all tests in the package 'com.example.services'
Step 4: Verify that all test classes in 'com.example.services' package are executed
✅ Expected Result: All tests in the specified packages run successfully and report correct pass/fail status
Automation Requirements - JUnit 5
Assertions Needed:
Verify test execution count matches number of test classes in package
Verify all tests pass in the package
Best Practices:
Use JUnit Platform Launcher API to run tests by package
Use assertions to verify test results
Organize tests in packages matching source code structure
Automated Solution
JUnit
import org.junit.platform.engine.DiscoverySelector;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.LauncherFactory;
import org.junit.platform.launcher.listeners.SummaryGeneratingListener;
import org.junit.platform.launcher.listeners.TestExecutionSummary;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class PackageLevelTestRunner {

    public static void main(String[] args) {
        runTestsInPackage("com.example.utils");
        runTestsInPackage("com.example.services");
    }

    private static void runTestsInPackage(String packageName) {
        LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
                .selectors(DiscoverySelectors.selectPackage(packageName))
                .build();

        Launcher launcher = LauncherFactory.create();
        SummaryGeneratingListener listener = new SummaryGeneratingListener();

        launcher.registerTestExecutionListeners(listener);
        launcher.execute(request);

        TestExecutionSummary summary = listener.getSummary();

        System.out.println("Package: " + packageName);
        System.out.println("Tests found: " + summary.getTestsFoundCount());
        System.out.println("Tests succeeded: " + summary.getTestsSucceededCount());
        System.out.println("Tests failed: " + summary.getTestsFailedCount());

        // Assertions to verify all tests passed
        assertTrue(summary.getTestsFoundCount() > 0, "No tests found in package " + packageName);
        assertEquals(0, summary.getTestsFailedCount(), "Some tests failed in package " + packageName);
    }
}

This code uses JUnit 5's Launcher API to run all tests in a given package.

The runTestsInPackage method builds a discovery request selecting the package, then executes it with a launcher.

A SummaryGeneratingListener collects test results.

After execution, it prints the number of tests found, succeeded, and failed.

Assertions check that at least one test was found and that no tests failed.

This approach ensures package-level test organization is verified by running all tests in the package and checking their results.

Common Mistakes - 3 Pitfalls
Using hardcoded test class selectors instead of package selectors
Not checking if any tests were found before asserting success
Ignoring test failures and not asserting on them
Bonus Challenge

Now add data-driven testing with 3 different package names to run tests dynamically

Show Hint

Practice

(1/5)
1. Why is it recommended to organize JUnit test classes in the same package as the source code they test?
easy
A. JUnit requires tests to be in the same package to run.
B. It makes tests easier to find and run selectively.
C. It prevents tests from accessing package-private code.
D. It automatically runs tests without any configuration.

Solution

  1. Step 1: Understand package organization purpose

    Organizing tests in the same package as source code helps developers find related tests quickly.
  2. Step 2: Benefits of package-level organization

    This organization allows running tests selectively by package and keeps the project clean and maintainable.
  3. Final Answer:

    It makes tests easier to find and run selectively. -> Option B
  4. Quick Check:

    Package-level test organization = easier test management [OK]
Hint: Tests in same package as code = easier to find and run [OK]
Common Mistakes:
  • Thinking JUnit forces tests in same package
  • Believing tests cannot access package-private code
  • Assuming tests run automatically without setup
2. Which of the following is the correct way to place a JUnit test class for a source class com.example.service.UserService?
easy
A. In package com.example under the test source folder
B. In package com.example.test under the main source folder
C. In package com.example.service under the main source folder
D. In package com.example.service under the test source folder

Solution

  1. Step 1: Identify source package and test source folder

    The source class is in com.example.service. Tests should be in the same package but under the test source folder.
  2. Step 2: Match test class package and location

    In package com.example.service under the test source folder places the test class in com.example.service under the test source folder, which is correct.
  3. Final Answer:

    In package com.example.service under the test source folder -> Option D
  4. Quick Check:

    Test package = source package + test folder [OK]
Hint: Test package matches source package but in test folder [OK]
Common Mistakes:
  • Placing tests in main source folder
  • Changing package name for tests
  • Putting tests in unrelated packages
3. Given the following project structure:
src/main/java/com/app/utils/Calculator.java
src/test/java/com/app/utils/CalculatorTest.java

What will happen if you run tests only in package com.app.utils?
medium
A. No tests will run because package is incorrect.
B. All tests in the project will run.
C. Only CalculatorTest will run.
D. Tests in other packages will also run.

Solution

  1. Step 1: Understand package-based test running

    Running tests in package com.app.utils runs only tests in that package.
  2. Step 2: Identify test classes in that package

    CalculatorTest is in com.app.utils, so it will run; tests in other packages won't.
  3. Final Answer:

    Only CalculatorTest will run. -> Option C
  4. Quick Check:

    Run tests by package runs only that package's tests [OK]
Hint: Run tests by package runs only tests in that package [OK]
Common Mistakes:
  • Assuming all tests run regardless of package
  • Thinking package name is case-insensitive
  • Believing tests outside package run automatically
4. You have a test class com.example.service.OrderServiceTest placed under src/main/java/com/example/service. What is the problem with this setup?
medium
A. Tests should not be placed in the main source folder.
B. Package name is incorrect for tests.
C. Test class name should not end with 'Test'.
D. JUnit does not support tests in com.example.service.

Solution

  1. Step 1: Identify source folder for tests

    Tests must be placed under the test source folder, not the main source folder.
  2. Step 2: Analyze the given setup

    The test class is in the main source folder, which is incorrect and can cause build or test execution issues.
  3. Final Answer:

    Tests should not be placed in the main source folder. -> Option A
  4. Quick Check:

    Tests belong in test source folder, not main [OK]
Hint: Tests must be in test source folder, not main source [OK]
Common Mistakes:
  • Placing tests in main source folder
  • Changing package names unnecessarily
  • Misnaming test classes
5. You want to organize tests for a multi-module project where each module has its own source and test folders. How should you organize package-level tests to keep the project clean and maintainable?
hard
A. Place test classes in the same package as source classes within each module's test folder.
B. Put all test classes in a single global test package for the entire project.
C. Place test classes in the main source folder to share with source code.
D. Use different package names for tests to avoid confusion.

Solution

  1. Step 1: Understand multi-module project structure

    Each module has separate source and test folders, so tests should mirror source package structure inside each module's test folder.
  2. Step 2: Benefits of matching test packages per module

    This keeps tests organized, easy to find, and maintainable per module without mixing unrelated tests.
  3. Final Answer:

    Place test classes in the same package as source classes within each module's test folder. -> Option A
  4. Quick Check:

    Match test packages to source packages per module [OK]
Hint: Match test packages to source packages inside each module [OK]
Common Mistakes:
  • Putting all tests in one global package
  • Mixing test and main source folders
  • Using different package names for tests
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard