Wednesday, December 06, 2023

SpringBootApplication Simple Unit Test

This is an example of how to call SpringBootApplication "Application.main" in a Java unit test.

You should have setup a Spring Boot application already.

Here is an example of a simple Application class.

@SpringBootApplication(scanBasePackages = {"com.company.stuff"})
public class Application
{

    private static ConfigurableApplicationContext configurableApplicationContext = null;

    public static void main(String[] args)
    {
        configurableApplicationContext = SpringApplication.run(Application.class, args);
    }

    public static void shutdown()
    {
        if(null != configurableApplicationContext) {
            SpringApplication.exit(configurableApplicationContext);
        }
    }

}


Here is an example of a unit test that starts the application on a specified port, makes a call to the application via a RestTemplate, and then shuts down the application.



public class ApplicationMainTest
{
    RestTemplate restTemplate = new RestTemplate();

    @Test
    public void testMain() throws Exception {

        try {
            Application.main(new String[]{"--server.port=8093"});

            String url = "http://localHost:8093";
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            assertNotNull(response);

        }
        catch (Exception ignored) {
            //ignored
        }
        finally {
            Thread.sleep(10000);
            Application.shutdown();
        }
    }
}

No comments: