What is interest to use an embedded Tomcat server when testing web layer in spring boot?

26 Views Asked by At

I'm trying to understand the difference between these two annotations...

this one, which makes starting a real embedded server at starting

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

and this one, which do not start any http server..

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)

Of course, when I use the first on (SpringBootTest.WebEnvironment.RANDOM_PORT), I got this log at starting:

2023-12-16T16:07:40.816+01:00  INFO 25939 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 0 (http)
2023-12-16T16:07:40.826+01:00  INFO 25939 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-12-16T16:07:40.826+01:00  INFO 25939 --- [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.16]
2023-12-16T16:07:40.879+01:00  INFO 25939 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-12-16T16:07:40.881+01:00  INFO 25939 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1677 ms

So, my question is: what is the interest of using an embedded http server when testing as results are the same.

To be precise, I use this kind of code:

// results are the same, with WebEnvironment.MOCK
// or WebEnvironment.RANDOM_PORT !!    
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@AutoConfigureMockMvc
class TestExample {

    @Autowired
    MockMvc mockMvc;

    @Test
    void test() throws Exception {
        mockMvc.perform(get("/api/v1/first")
                        .accept(MediaType.ALL))
                .andExpect(status().isOk())
                .andExpect(content().string("mocked body")
                );
    }

}
0

There are 0 best solutions below