How to create JUnit Test Suite? (with Examples)

On This Page What is a JUnit Test Suite?JUnit 4 vs. JUnit 5April 24, 2026 · 16 min read · Testing Guide

How to make JUnit Test Suite? (with Examples)

As software projects scale, managing and executing tests efficiently turn indispensable. JUnit Test Suites render a potent way to organize and execute test in a structured style, particularly in complex applications. By grouping related test cases, developers can streamline the testing process, saving time and resources.

Overview

A JUnit Test Suite allows developers to bundle multiple test classes and run them together, making it easier to handle and fulfil related tests in a individual flow.

Benefits of Using JUnit Test Suite:

  • Run multiple trial classes together efficiently
  • Organize and construction tests for better maintainability
  • Save clip by executing sorted tests in one go
  • Streamline fixation and continuous integration testing
  • Maintain consistent test execution across modules

This article explores the concept of a JUnit Test Suite, comparing JUnit 4 vs. JUnit 5, and discussing the objective, welfare, and categories of test suites. It covers practical JUnit Test Suite examples for both existing and new projects, including advanced techniques, rules, extensions, and good exercise.

What is a JUnit Test Suite?

In large-scale labor, multiple scenario must be essay to ensure. In order to streamline the process, related are often group into test suites.

This approach allows testers to accomplish specific sets of tests based on demand, which is particularly useful when some tests are time-consuming or rely on external dependencies like API phone. These selective executions help avoid unneeded overhead and meliorate test efficiency.

A JUnit examination suite enable the grouping and execution of exam cases across multiple classes. Instead of running each class severally, a test suite countenance multiple examination to run together, making the testing process more organized and efficient.

This grouping is especially important for care different types of tests, such as,, or slow-running tests.

JUnit 4 vs. JUnit 5

JUnit has evolved significantly between adaptation 4 and 5, with renowned improvements in flexibility and modern language support.

JUnit 4:

  • The intact framework is packaged in a single JAR file, meaning all features are imported even if only a subset is require.
  • Supports only one examination runner at a time (e.g., SpringJUnit4ClassRunner or Parameterized), circumscribe flexibility in unite different testing strategies.
  • Was design before Java 8 and does not leverage newer language feature such as lambda expressions or streams.

JUnit 5:

  • Introduces a modular architecture, allowing developer to import only the necessary components.
  • Supports multiple tryout contrabandist (via extension), enable more flexible and powerful test execution strategies.
  • Fully embraces Java 8 and later versions, offering unclouded syntax and more expressive test definition.
  • Represents a complete redesign of the JUnit framework, addressing many of the limit found in JUnit 4.

Overall, JUnit test suites are all-important for structured testing in complex application, and JUnit 5 provides a more modern, flexible, and efficient approaching to test suite direction.

While JUnit test suites assist organize and execute tests expeditiously, running them across real-world environs, browser, device, and operate systems can still be a challenge.

Platforms like enable teams to run JUnit-based or tests on existent device and browser in the cloud, eliminating the motivation to maintain test infrastructure.

Benefits of Using a Test Suite

The primary benefits of using a test rooms include:

  • Organized Testing:Groups related test cases for easier provision and performance.
  • Comprehensive Coverage:Combines and test types within a individual retinue.
  • Open Purpose:Documents the intention behind each tryout cause, help traceability.
  • Defined Criteria:Includes particular such as software version, operating system, and dependencies.
  • Customizable Structure:Can be tailored based on test frequency, complexness, or scope.
  • Faster Execution:Allows for efficient, repeatable testing, particularly during regression or uninterrupted consolidation cycles.

By creating test suites tailored to different, such as functional,, or, you can streamline and amend collaboration between QA and business teams.

Read More:

Test Suite Categories

Test suites can be dissever into two main categories based on their purpose and level of abstract:

  • Nonobjective Test Suite:A high-level set of test cases derived from a poser of the system under exam (SUT). It outlines testing objectives and system behavior but lacks implementation particular, do it non-executable. It serves as a pattern for creating executable tests.
  • Workable Test Suite:A elaborate, runnable set of test cases deduct from abstract tests. It includes specific instructions that interact forthwith with the scheme under test (SUT), enabling automatize or manual execution to verify functionality.

Read More:

How to run JUnit Test Suite?

To run a JUnit test retinue, it ’ s essential to understand how to create and organize it. The following sections outline different slipway to set up a test suite.

1. Creating a Test Suite for an Existing Project

Follow these steps to develop a test suite in Eclipse:

  1. Navigate to the project where you require to create the test cortege in Eclipse.
  2. In the package explorer pane, right-click on the project and choose & # 8220; New & # 8221; from the context menu.
  3. Select & # 8220; JUnit & # 8221; from the list of available alternative in the new window, followed by & # 8220; JUnit Test Suite & # 8221; from the sub-menu.
  4. To move to the next measure, use the & # 8220; Next & # 8221; button.
  5. The gens and location of the test entourage can be fix in the following box. Make certain to take a location.
  6. To complete the tryout suite, click the & # 8220; Finish & # 8221; button.
  7. After you & # 8217; ve created the test suite, you can add individual tryout instance by right-clicking on it in the Package Explorer pane and selecting & # 8220; Add New Test & # 8221; from the context menu.
  8. In the future window, you can give the new test case a name and a location. Make certain that you take a location within the test suite & # 8217; s software.
  9. To complete the examination scenario, click the & # 8220; Finish & # 8221; button.
  10. Repeat the preceding steps to add more test cases to the test suite.
  11. Once you & # 8217; ve added all of the trial cases to the tryout suite, you can run it by right-clicking on it in the Package Explorer dot and selecting & # 8220; Run As & # 8221; for & # 8220; JUnit Test & # 8221; from the context menu.
  12. This will run all test event in the test suite and show the results in the JUnit scene.

2. Creating a Test Suite for a New Project

The procedures below can be utilize to construct a test suite in Eclipse:

  1. Navigate to the project where you need to build the tryout retinue in Eclipse.
  2. Right-click the project in the software explorer pane and choose & # 8220; New & # 8221; from the context menu.
  3. Pick & # 8220; JUnit & # 8221; from the drop-down menu in the new window, so pluck & # 8220;JUnit Test Suite& # 8221; from the sub-menu.
  4. To move on to the future form, click & # 8220; Next & # 8221;.
  5. You can specify the test suite & # 8217; s name and localization in the following window. Choose a situation that is located in the project & # 8217; s source folder.
  6. To finish make the trial entourage, pawl & # 8220; Finish & # 8221;.
  7. Individual test instance can be added to a test suite after it has been created by right-clicking the exam suite in the Package Explorer pane and choosing & # 8220; Add New Test & # 8221; from the context menu.
  8. The name and localization of the new test case can be inscribe in the following window. Select a location from the trial retinue & # 8217; s package carefully.
  9. To finish creating the test case, click & # 8220; Finish & # 8221;.
  10. Follow the same procedure to add more test lawsuit to the test retinue.
  11. The test suite can be performed entirely when all test cases hold been create by right-clicking on the test rooms in the Package Explorer pane and choosing & # 8220; Run As & # 8221; for & # 8220; JUnit Test & # 8221; from the context menu.

3. Creating a Test Suite for Different Test Types

A exam suite is a collection of test cases grouped together to execute and track testing advance. It plays a key role in by helping teams organize test cases found on prove objectives, contrive needs, or analysis requirements.

For model, a test suite for a product purchasing workflow might include:

  • Test Case 1: Login
  • Test Case 2: Add Products to Cart
  • Test Case 3: Checkout
  • Test Case 4: Logout

Talk to an Expert

Creating a Canonical JUnit Test Suite

A JUnit test suite example can be well understood by setting up a sample project.

  • A exam suite grouping and runs several unit test cases at once. The suite tests in JUnit are execute using both the @ RunWith and @ Suite annotations. This subdivision uses TestJunit1 and TestJunit2 as two test grade running simultaneously using the Test Suite.
  • Make a trial Java class under C: \ & gt; JUNIT_WORKSPACE, such as MessageUtil.java.
/ * * This category prints the given content on console. * / public course MessageUtil {private String substance; //Constructor public MessageUtil (String content) {this.message = content;} // prints the message public String printMessage () {System.out.println (message); return message;} public String salutationMessage () {message = `` Hello! '' + content; System.out.println (substance); return substance;}}

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

Read More:

Creating Test Classes

  • In C: \ & gt; JUNIT_WORKSPACE, create a Java family file phone TestJunit1.java.
signification org.junit.Test; signification org.junit.Ignore; import unchanging org.junit.Assert.assertEquals; public class TestJunit1 {String message = `` Robert ''; MessageUtil messageUtil = new MessageUtil (message); @ Test public void testPrintMessage () {System.out.println (`` Inside testPrintMessage () ''); assertEquals (substance, messageUtil.printMessage ());}}
  • In C: \ & gt; JUNIT_WORKSPACE, create a Java class file called TestJunit2.java.
import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.assertEquals; public family TestJunit2 {String substance = `` Robert ''; MessageUtil messageUtil = new MessageUtil (substance); @ Test public void testSalutationMessage () {System.out.println (`` Inside testSalutationMessage () ''); content = `` Hello! '' + `` Robert ''; assertEquals (message, messageUtil.salutationMessage ());}}

Creating a Test Suite

  • Construct a Java form.
  • Add the notation @ RunWith (Suite.class) to the family.
  • Making use of the @ Suite.SuiteClasses annotation, add references to JUnit tryout course.
  • To run the test instance (s), make a Java form file called TestSuite.java in C: \ & gt; JUNIT_WORKSPACE.
signification org.junit.runner.RunWith; import org.junit.runners.Suite; @ RunWith (Suite.class) @ Suite.SuiteClasses ({TestJunit1.class, TestJunit2.class}) public class JunitTestSuite {}
  • Create Test Runner Class
  • To fulfil the test case (s), make a java category file named TestRunner.java in C: \ & gt; JUNIT_WORKSPACE.
import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner {public static void main (String [] args) {Result result = JUnitCore.runClasses (JunitTestSuite.class); for (Failure failure: result.getFailures ()) {System.out.println (failure.toString ());} System.out.println (result.wasSuccessful ());}}

Running the Test Suite

  • Compile all of the Java family with javac.
C: \JUNIT_WORKSPACE & gt; javac MessageUtil.java TestJunit1.java TestJunit2.java JunitTestSuite.java TestRunner.java

Execute the, which will fulfill the test case delineate in the specified Test Case category.

C: \JUNIT_WORKSPACE & gt; java TestRunner

Check the output.

Inside testPrintMessage () Robert Inside testSalutationMessage () Hello Robert true

Grouping Tests using JUnit Test Suite

You require your to execute as tight as possible and provide you with as much info as potential at the beginning of a well-organized build procedure. Having the option to organise your tests into distinct groups is a helpful pawn for this.

  • This can assist you recount the difference between quick-running unit tests and longer-running integration, execution, load, or acceptance examination, for instance.
  • Using JUnit Categories, you can organize your tryout into ordered group and run them independently of one another. For case, you can distinguish between fast and dull examination.
  • Annotations allow you to choose which classes to include or dismiss. The @ Category annotation is available for labeling test cases and method with one of these radical.

Read More:

Grouping Tests expend JUnit Categories

You ask to establish your categories firstly: FastTests and SlowTests.

FastTests.java

public interface FastTests {/ * category marker * /}

SlowTests.java

public interface SlowTests {/ * family marking * /}

A class or an interface can both be regard categories. Method b () of class A is annotated with the @ category keyword in the codification below.

Indicating that method b () fall under the SlowTests category. By doing this, you were able to mark each exam method separately in addition to the entire class.

import org.junit.Test; import org.junit.experimental.categories.Category; public family A {@ Test public void a () {System.out.println (`` a () method of category A has be run ... \n '');} @ Category (SlowTests.class) @ Test public void b () {System.out.println (`` b () method of class A has been run ... \n '');}}

Class B is mark with the @ Category annotation in the code below. As a result, this class includes all of the test methods for this tryout stratum.

You can see that a test class or test method can be categorized under multiple family.

import org.junit.Test; import org.junit.experimental.categories.Category; @ Category ({SlowTests.class, FastTests.class}) public course B {@ Test public void c () {System.out.println (`` c () method of grade B has be run ... \n '');}}

Running Test Groups

  • You can see that the name of your test rooms is SlowTestFirstSuite in the code below.
  • A test retinue can also be categorise. Which class will be execute are show by the annotation @ IncludeCategory.
  • The SlowTest category is present in the representative below and will be used.
  • As a result, the test methods b () of class A and c () of category B will be run.
SlowTestFirstSuite.java import org.junit.experimental.categories.Categories; import org.junit.runner.RunWith; import org.junit.runners.Suite; @ RunWith (Categories.class) @ Categories.IncludeCategory (SlowTests.class) @ Suite.SuiteClasses ({A.class, B.class}) // Note that Categories is a variety of Suite public class SlowTestsFirstSuite {// b () method of form A has been run ... // c () method of class B has been run ...}
  • The code below has an annotating called @ ExcludeCategory that specifies which categories will not be executed.
  • The test method b () of class A will be run in the codification sample below, but method a () and c () of class A and class B won & # 8217; t be run because they are except from execution by the @ ExcluedeCategory annotation.
  • Because it is not in any category, the test method a () of category A will not be run in either scenario.
import org.junit.experimental.categories.Categories; import org.junit.runner.RunWith; significance org.junit.runners.Suite; @ RunWith (Categories.class) @ Categories.IncludeCategory (SlowTests.class) @ Categories.ExcludeCategory (FastTests.class) @ Suite.SuiteClasses ({A.class, B.class}) // Note that Categories is a kind of Suite public class SlowTestsSecondSuite {//b () method of class A has been run ...}

Advanced JUnit Test Suite Techniques

In a test class, JUnit enable developers to use parameters.

  • Using the annotating, the test class can be name as a parameterized trial: @ RunWith (Parameterized.class)
  • A inactive method with the @ Parameters annotation that create
  • s and returns a Collection of Arrays must be present in the trial class. Each aim in this collection is one of the test method & # 8217; s parameters.
  • When a parameterized test course is run, example of the test methods and the test data components are produced for the cross-product (binary operation of two arrays).
  • Each trial & # 8217; s values will be stored in the public constructor. The number of elements in each array that is supply by the method with the @ Parameters annotation must jibe the bit of constituent in the builder of the class. The builder passes each parameter & # 8217; s class and exam values to the class.
  • In JUnit 5, the Assumptions class allows you to use static methods to set conditions for examination performance. These conditions will be ground on your assumptions; if one fail, the exam will be aborted (rather than miscarry, as with assertions). They let you to programmatically determine whether to continue running tests, saving you a significant amount of time and perhaps computing bandwidth during testing.
  • It can be useful to temporarily disregard some test scenarios. You can use the @ Disabled annotation to keep those tests (individual examination methods or entire test classes) from running. In the trial story, any @ Disabled test method will be noted as handicapped. @ Disabled allows you to indicate a rationale for deactivating the test as a argument.
  • Nested test classes can be used to organize test that should be together logically.
  • Using the @ Timeout note allows you to specify a maximum time for the executing of a test method. If the test takes longer to execute than the duration you take (which is by default defined in second), @ timeout will just fail the test.

Also Read:

Using JUnit Rules

  • A rule changes how a test method or method are conducted or describe.
  • The @ Rule annotation indicate that the stratum implements the TestRule interface.
  • The @ ClassRule annotation corresponds to the TestRule form.
  • Rules countenance you to write code to inspect a trial before it is run, change how and whether it is run, and inspect and alter the test effect.
  • A rule implementation can intercept test method performance and vary the behavior of these tests, or it can include cleaning work like @ Before, @ After, @ BeforeClass, and @ AfterClass.
  • The normal notion is similar to JUnitRunners, but with the added feature of combining different prescript. When combining many Runners, it is best to use regulation cases.

Using JUnit Extensions

JUnit 5 extensions are colligate with a specific event during test execution cognise as an propagation point. The JUnit engine invokes registered extensions when a given living cycle phase is reached.

Five primary types of propagation points can be used:

  • test instance post-processing
  • conditional test performance
  • life-cycle callbacks
  • parameter declaration
  • elision plow

To construct a JUnit 5 extension, you must specify a grade that implements one or more interfaces match to the JUnit 5 extension points. These interfaces continue the nucleus Extension interface, which is merely a mark interface.

Best Practices for JUnit Test Suites

To ensure efficient and effectual use of JUnit Test Suites, the following better practices should be followed.

1. Naming Conventions

  • The exam names should be insightful, and users should be able to grasp the test & # 8217; s behavior and anticipation simply by appear at the name.
  • givenEmployeeObject_whenSaveEmployee_thenReturnSavedEmployee
  • givenEmployeesList_whenFindAll_thenReturnListOfEmployees
  • givenEmployeeObject_whenUpdateEmployee_thenReturnUpdatedEmployee

2. Test Organization

  • Separating the test classes from the product codification is recommended. This means they are create, run, and maintained severally from the code used in production.
  • In addition, it eliminates the peril of having ontogeny codification executed in the production environment.

3. Test Suite Maintenance

  • Make sure that each test is written severally of the others.
  • So, whenever you indite multiple Unit tests, ensure that they are all autonomous of one another. This will assist you in determining the theme problem and correctly testing the logic unit.
  • Use the @ BeforeEach and @ AfterEach annotations to put up any prerequisites for all of your test causa. The @ BeforeEach and @ AfterEach method in the current class execute before and after each method annotated with @ Test, @ RepeatedTest, @ ParameterizedTest, or @ TestFactory.
  • JUnit conducts tests in any sequence by default. To qualify the order of test executing, simply footnote your test class with @ FixMethodOrder and blame one of the uncommitted MethodSorters:
  • @ FixMethodOrder (MethodSorters.JVM): Leaves the tryout method in the order returned by the JVM. This order may differ from run to run.
  • @ FixMethodOrder (MethodSorters.NAME_ASCENDING): Sorts the tryout method in lexicographical order by the method name.

What is the use of cortege in JUnit 5?

The @ Suite annotation is used to make test suites in JUnit 5. Suites facilitate the execution of tests dispersed over various classes and parcel. To narrow down your test cases, you can take reward of the Include and Exclude annotations.

To specify which tests should be included or excluded from a given suite, JUnit 5 offers the undermentioned annotations.

  • @ SelectClasses
  • @ SelectPackages
  • @ IncludePackages
  • @ ExcludePackages
  • @ IncludeClassNamePatterns
  • @ ExcludeClassNamePatterns
  • @ IncludeTags
  • @ ExcludeTags

Conclusion

JUnit Test Suites play a critical role in structuring and streamline the quiz process, specially in bombastic and complex applications. By grouping related test cases, they enable efficient execution, better organization, and improved test coverage.

With the flexibility offered by JUnit 5, squad can adopt more modular and scalable testing strategy use prescript, extensions, and advance suite configurations. Implementing best practices farther enhances the reliability and maintainability of examination suites, making them a valuable asset in any development workflow.

To take testing a footstep further, integrating trial suites with a scalable and real-world execution environment is key. BrowserStack Automate empowers teams to run JUnit-based Selenium and Appium tests across 3500+ real browser and twist combination, directly from the cloud. It supports:

  • executing to drastically trim exam runtime
  • Local testing for staging environments behind firewall
  • features like video recording, screenshots, logs, and detailed debugging
  • Zero maintenance of infrastructure, allowing squad to rivet purely on examination logic

By combining the power of JUnit Test Suites with BrowserStack Automate, ontogenesis and QA team can assure faster feedback, high coverage, and more reliable package, deliver at scale and hurrying.

Tags
19,000+ Views

# Ask-and-Contributeabout this subject with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free