在一個專案中,我有一個使用 bean B1 和 B2 的服務 A。如果我想為服務A創建一個集成測驗,我通常會像這樣創建測驗類:
@SpringBootTest(classes = {A.class, B1.class, B2.class})
@ActiveProfiles("test")
class AIntegrationTest {
...
}
我的問題:這種方法好還是有一個干凈的解決方案?
uj5u.com熱心網友回復:
這是 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");
}
}
uj5u.com熱心網友回復:
不確定您甚至需要在 @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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/342754.html
上一篇:為集成測驗/@SpringBootTest提供bean時出現BeanDefinitionOverrideException
