在 Spring Boot 中测试 Web 层时使用嵌入式 Tomcat 服务器有什么好处?

问题描述 投票:0回答:1

我试图理解这两个注释之间的区别...

这个,它可以在启动时启动一个真正的嵌入式服务器

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

还有这个,它不启动任何http服务器..

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)

当然,当我在

(SpringBootTest.WebEnvironment.RANDOM_PORT)
上使用第一个时,我在开始时得到了这个日志:

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

所以,我的问题是:当测试结果相同时,使用嵌入式 http 服务器有什么好处。

准确来说,我用的是这样的代码:

// 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")
                );
    }

}
spring-boot testing spring-annotations
1个回答
0
投票

请查看这篇文章webEnvironment = RANDOM_PORT 和 webEnvironment = MOCK 之间的区别 在这里您可以找到问题的答案。

© www.soinside.com 2019 - 2024. All rights reserved.