multiple instance of Spring boot application in JUnit test

Viewed 1206

Is it possible to have a Junit test that starts two instances (on separate threads) of the application, so that resilience can be tested?

I came across an idea (Instantiate multiple spring boot apps in test) of starting the application using : new SpringApplicationBuilder(Application.class).build().run()

This works well to test a single instance at a time, my problem arises when I start a second instance of the application while the first is running in a separate thread.

The application contexts of the two seem to bleed across, or possibly the second one completely overwrites the first? I've put some breakpoints in the test, and I can see the first context (nodeA), and get a bean from it that has the correct value in ID field (caretakerA). After the second context has started, if i get the same bean from both contexts (nodeA & nodeC) that ID property will be the same (caretakerC).

Before Second context is started watch expressions BREAK 1 in code

After Second context is started watch expressions BREAK 2 in code

I've included the test code below, many thanks for any ideas.

public class ResilienceTests
{
    @Test
    public void testResilience1() throws InterruptedException
    {    

        SpringApp nodeA = new SpringApp("caretakerA", "8181");
        nodeA.start();

        Thread.sleep(2000);
        SpringApp nodeC = new SpringApp("caretakerC", "8383");
        // Break point 1
        nodeC.start();
        // Break point 2
        ConfigurableApplicationContext contextA = nodeA.getContext();

        Thread.sleep(60000);
     }

    class SpringApp extends Thread
    {
        private ConfigurableApplicationContext context;
        private String propsName;
        private String port;

        public SpringApp(String name, String port)
        {
            super(name);
            this.propsName = name;
            this.port = port;
        }

       @Override
        public void run()
        {
            System.err.println("ENTERING RUN()");
            context = new SpringApplicationBuilder(Application.class)
                    .properties("spring.config.name:" + propsName,
                            "server.port:" + port,
                            "resilience.system.id:" + propsName)
                    .build()
                    .run();
            System.err.println("RETURNING FORM RUN()");
            System.err.println("CONTEXT IS " + context == null ? "NULL" : " NOT NULL");
        }

        public ConfigurableApplicationContext getContext()
        {
            return this.context;
        }
    }
}
0 Answers
Related