[英]Is it the best approach to do an integration test in spring boot?
在一個項目中,我有一個使用 bean B1 和 B2 的服務 A。 如果我想為服務A創建一個集成測試,我通常會像這樣創建測試類:
@SpringBootTest(classes = {A.class, B1.class, B2.class})
@ActiveProfiles("test")
class AIntegrationTest {
...
}
我的問題:這種方法好還是有一個干凈的解決方案?
理想情況下,您希望擺脫classes = {A.class, B1.class, B2.class}
並只使用 @SpringBootTest 注釋。 這將確保為test
和production
構建相同的上下文。
更重要的是,在這種情況下,上下文將被 spring 測試運行器緩存,並被需要相同類型上下文的測試重用。
不確定您甚至需要在 @SpringBootTest 注釋中定義 bean。 要么@Mock 類與mockito 到@Autowire 他們
// here's an example from the web
@RunWith(SpringRunner.class)
@SpringBootTest(
SpringBootTest.WebEnvironment.MOCK,
classes = Application.class)
@AutoConfigureMockMvc
@TestPropertySource(
locations = "classpath:application-integrationtest.properties")
public class EmployeeRestControllerIntegrationTest {
@Autowired
private MockMvc mvc;
@Autowired
private EmployeeRepository repository;
// write test cases here
}
這是 spring 文檔中的另一個示例。
package com.example.testingweb;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class HttpRequestTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
public void greetingShouldReturnDefaultMessage() throws Exception {
assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/",
String.class)).contains("Hello, World");
}
}
出於多種原因,我建議避免使用 SpringBoot 編寫集成測試,包括但不限於運行集成測試所需的時間。 一些問題可以在這里閱讀https://medium.com/swlh/the-devil-that-is-springboottest-68b7f4148bb6
最好的方法是在測試環境中部署一個應用程序,並使用Cypress
、 Postman
等創建一套自動化測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.