Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test the SpringBoot application startup

I have a JUnit test that starts an spring-boot application (in my case, the main class is SpringTestDemoApp) after the test:

@WebIntegrationTest
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringTestDemoApp.class)
public class SpringTest {

    @Test
    public void test() {
        // Test http://localhost:8080/ (with Selenium)
    }
}

Everything works fine using spring-boot 1.3.3.RELEASE. Nevertheless, the annotation @WebIntegrationTest and @SpringApplicationConfiguration have been removed in spring-boot 1.5.2.RELEASE. I tried to refactor the code to the new version, but I am not able to do it. With the following test, my app is not started before the test and http://localhost:8080 returns 404:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringTestDemoApp.class)
@WebAppConfiguration
public class SpringTest {

    @Test
    public void test() {
        // The same test than before
    }

}

How can I refactor my test to make it works in spring-boot 1.5?

like image 688
Boni García Avatar asked Apr 07 '17 15:04

Boni García


People also ask

How does a spring boot application start?

Spring Boot automatically configures your application based on the dependencies you have added to the project by using @EnableAutoConfiguration annotation. For example, if MySQL database is on your classpath, but you have not configured any database connection, then Spring Boot auto-configures an in-memory database.


1 Answers

The webEnvironment option inside @SpringBootTest is very important. It can take values like NONE, MOCK, RANDOM_PORT, DEFINED_PORT.

  • NONE will only create spring beans and not any mock the servlet environment.

  • MOCK will create spring beans and a mock servlet environment.

  • RANDOM_PORT will start the actual servlet container on a random port; this can be autowired using the @LocalServerPort.

  • DEFINED_PORT will take the defined port in the properties and start the server with it.

The default is RANDOM_PORT when you don’t define any webEnvironment. So the app may be starting at a different port for you.

Try to override it to DEFINED_PORT, or try to autowire the port number and try to run test on that port.

like image 121
Praneeth Ramesh Avatar answered Sep 27 '22 19:09

Praneeth Ramesh