Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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 – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

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

Accessibility testing is a crucial aspect to ensure that your application is usable for everyone and meets accessibility standards that are required in many countries.

By automating these tests, teams can quickly detect issues related to screen reader compatibility, keyboard navigation, color contrast, and other aspects that could pose a barrier to using the software effectively for people with disabilities.

Learn how to automate accessibility testing with Selenium and the LambdaTest cloud-based testing platform that lets developers and testers perform accessibility automation on over 3000+ real environments:

Automated Accessibility Testing With Selenium

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

Accessibility testing is a crucial aspect to ensure that your application is usable for everyone and meets accessibility standards that are required in many countries.

By automating these tests, teams can quickly detect issues related to screen reader compatibility, keyboard navigation, color contrast, and other aspects that could pose a barrier to using the software effectively for people with disabilities.

Learn how to automate accessibility testing with Selenium and the LambdaTest cloud-based testing platform that lets developers and testers perform accessibility automation on over 3000+ real environments:

Automated Accessibility Testing With Selenium

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.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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

Partner – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

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

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