eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI (cat= Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

1. Overview

The main() method serves as the starting point for each Java application, and it might look different depending on the app type. In the case of regular web applications, the main() method will be responsible for context start, but in the case of some console applications, we’ll put business logic to it.

Testing the main() method is quite complex because we have a static method that accepts only string arguments and returns nothing.

In this article, we’ll figure out how to test the main method focusing on command-line arguments and input streams.

2. Maven Dependencies

For this tutorial, we’ll need several testing libraries (Junit and Mockito) as well as Apache Commons CLI in order to work with arguments:

<dependency>
     <groupId>commons-cli</groupId>
     <artifactId>commons-cli</artifactId>
     <version>1.6.0</version>
 </dependency>
 <dependency>
     <groupId>org.junit.jupiter</groupId>
     <artifactId>junit-jupiter-api</artifactId>
     <version>5.10.0</version>
     <scope>test</scope>
 </dependency>
 <dependency>
     <groupId>org.mockito</groupId>
     <artifactId>mockito-core</artifactId>
     <version>5.5.0</version>
     <scope>test</scope>
 </dependency>

We can find the latest versions of JUnit, Mockito, and Apache Commons CLI in the Maven Central repository.

3. Setting Up a Scenario

To illustrate main() method testing, let’s define a practical scenario. Imagine we’re tasked to develop a simple application that is designed to calculate the sum of provided numbers. It should be able to read an input, either interactively from the console or from a file, depending on the parameters provided. Program input comprises a series of numbers.

Based on our scenario, the program should dynamically adapt its behavior based on user-defined parameters, leading to the execution of diverse workflows.

3.1. Define Program Arguments With Apache Commons CLI

We need to define two essential arguments for the described scenario: “i” and “f”. The “i” option specifies the input source with two possible values (FILE and CONSOLE). Meanwhile, the “f” option allows us to specify a filename to read from, and it’s valid only in the case when the “i” option is specified as FILE.

To streamline our interaction with these arguments, we can rely on the Apache Commons CLI library. This tool not only validates parameters but also facilitates value parsing. Here’s an illustration of how the ‘i’ option can be defined using Apache’s Option builder:

Option inputTypeOption = Option.builder("i")
  .longOpt("input")
  .required(true)
  .desc("The input type")
  .type(InputType.class)
  .hasArg()
  .build();

Once we define our options, Apache Commons CLI will help to parse the input arguments to branch out the workflow of the business logic:

Options options = getOptions();
CommandLineParser parser = new DefaultParser();
CommandLine commandLine = parser.parse(options, args);

if (commandLine.hasOption("i")) {
    System.out.print("Option i is present. The value is: " + commandLine.getOptionValue("i") + " \n");
    String optionValue = commandLine.getOptionValue("i");
    InputType inputType = InputType.valueOf(optionValue);

    String fileName = null;
    if (commandLine.hasOption("f")) {
        fileName = commandLine.getOptionValue("f");
    }
    String inputString = inputReader.read(inputType, fileName);
    int calculatedSum = calculator.calculateSum(inputString);
}

To maintain clarity and simplicity, we segregate responsibilities into different classes. The InputType enum encapsulates possible input parameter values. The InputReader class retrieves input strings based on InputType, and the Calculator computes sums based on parsed strings.

Having such separation allows us to keep a simple main class like this:

public static void main(String[] args) {

    Bootstrapper bootstrapper = new Bootstrapper(new InputReader(), new Calculator());

    bootstrapper.processRequest(args);
}

4. How to Test the Main Method

The signature and behavior of the main() method are different from the regular methods we use in the app. Because of this, we need to combine multiple test strategies specific to testing static methods, void methods, input streams, and arguments.

We’ll cover each concept in the following paragraphs, but let’s first take a look at how the business logic of the main() method might be built.

When we are working on a new application, and we can fully control its architecture, then the main() method should not have any complex logic rather than initializing a needed workflow. Having such architecture, we can perform proper unit testing of each workflow part (Bootstrapper, InputReader, and Calculator can be tested separately).

On the other hand, when it comes to older applications with a history, things can get a bit trickier. Especially when previous developers have placed a lot of business logic directly in the main class’s static context. Legacy code is not always possible to change, and we should work with whatever is already written.

4.1. How to Test Static Methods

In the past, dealing with static contexts with Mockito was quite a challenge, often requiring the use of libraries like PowerMockito. However, in the latest versions of Mockito, this limitation has been overcome. With the introduction of Mockito.mockStatic in the 3.4.0 version, we can now easily mock and verify static methods without the need for additional libraries. This enhancement simplifies testing scenarios involving static methods, making our testing process more streamlined and efficient.

Using MockedStatic we can perform the same actions as with regular Mock:

try (MockedStatic<SimpleMain> mockedStatic = Mockito.mockStatic(StaticMain.class)) {
    mockedStatic.verify(() -> StaticMain.calculateSum(stringArgumentCaptor.capture()));
    mockedStatic.when(() -> StaticMain.calculateSum(any())).thenReturn(24);
}

In order to force MockedStatic to work as a Spy, we need to add one configuration parameter:

MockedStatic<StaticMain> mockedStatic = Mockito.mockStatic(StaticMain.class, Mockito.CALLS_REAL_METHODS)

As soon as we configure MockedStatic based on our needs, we can thoroughly test static methods.

4.2. How to Test Void Methods

Following functional development methodology, methods should conform to several requirements. They should be independent, should not modify incoming parameters, and should return processing results.

With such behavior, we can easily write unit tests based on returned result verification. However, testing void methods is different, and the focus shifts to the side effects and state changes caused by the method’s execution.

4.3. How to Test Program Arguments

We can invoke the main() method from a test class in the same way as any other standard Java method. To evaluate its behavior with different parameter sets, we only need to provide these parameters during the call.

Considering the Options definition from the previous paragraph, we can call our main() with a short argument -i:

String[] arguments = new String[] { "-i", "CONSOLE" };
SimpleMain.main(arguments);

Also, we can call the main method with the long form of the -i argument:

String[] arguments = new String[] { "--input", "CONSOLE" };
SimpleMain.main(arguments);

4.4. How to Test Data Input Stream

Reading from the console is usually built with System.in:

private static String readFromConsole() {
    System.out.println("Enter values for calculation: \n");
    return new Scanner(System.in).nextLine();
}

System.in it’s the “standard” input stream specified by the host environment, which usually corresponds to keyboard input. We cannot provide keyboard input in the test, but we can change the type of stream referenced by System.in:

InputStream fips = new ByteArrayInputStream("1 2 3".getBytes());
System.setIn(fips);

In this example, we’ve changed the default input type such that the app will read from ByteArrayInputStream and will not keep waiting for user input.

We can use any other type of InputStream in the test, for example, we can read from a file:

InputStream fips = getClass().getClassLoader().getResourceAsStream("test-input.txt");
System.setIn(fips);

Moreover, with the same approach, we can replace the output stream in order to verify what the program writes:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PrintStream out = new PrintStream(byteArrayOutputStream);
System.setOut(out);

With such an approach, we won’t see console output because System.out will send all the data to ByteArrayOutputStream instead of the console.

5. Complete Test Example

Let’s combine all the knowledge gathered in the previous paragraphs to write a complete test. These are the steps we are going to perform:

  1. Mock our main class as a spy
  2. Define input arguments as an array of String
  3. Replace default stream in System.in
  4. Verify that the program calls all required methods within the static context or that the program writes the necessary result to the console.
  5. Replace System.in and System.out streams back to original such that stream replacement will not affect other tests

In this example, we have a test for a StaticMain class where all logic is placed in a static context. We are replacing System.in with ByteArrayInputStream and building our verification based on the verify():

@Test
public void givenArgumentAsConsoleInput_WhenReadFromSubstitutedByteArrayInputStream_ThenSuccessfullyCalculate() throws IOException {
    String[] arguments = new String[] { "-i", "CONSOLE" };
    try (MockedStatic mockedStatic = Mockito.mockStatic(StaticMain.class, Mockito.CALLS_REAL_METHODS); 
      InputStream fips = new ByteArrayInputStream("1 2 3".getBytes())) {

        InputStream original = System.in;

        System.setIn(fips);

        ArgumentCaptor stringArgumentCaptor = ArgumentCaptor.forClass(String.class);

        StaticMain.main(arguments);

        mockedStatic.verify(() -> StaticMain.calculateSum(stringArgumentCaptor.capture()));

        System.setIn(original);
    }
}

We can use a slightly different strategy for the SimpleMain class because here we have distributed all business logic through other classes.

In this case, we do not even need to mock SimpleMain class because there are no other methods inside. We are replacing System.in with a file stream and building our verification based on the console output propagated to ByteArrayOutputStream:

@Test
public void givenArgumentAsConsoleInput_WhenReadFromSubstitutedFileStream_ThenSuccessfullyCalculate() throws IOException {
    String[] arguments = new String[] { "-i", "CONSOLE" };

    InputStream fips = getClass().getClassLoader().getResourceAsStream("test-input.txt");
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(byteArrayOutputStream);

    System.setIn(fips);
    System.setOut(out);

    SimpleMain.main(arguments);

    String consoleOutput = byteArrayOutputStream.toString(Charset.defaultCharset());
    assertTrue(consoleOutput.contains("Calculated sum: 10"));

    fips.close();
    out.close();
}

6. Conclusion

In this article, we’ve explored several main method designs along with their corresponding testing approaches. We’ve covered testing for static and void methods, handling arguments, and changing default system streams.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)