Course – LS – All
announcement - icon

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

>> CHECK OUT THE COURSE

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 complete examples are available over on GitHub.

Course – LS – All
announcement - icon

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

>> CHECK OUT THE COURSE

res – REST with Spring (eBook) (everywhere)