![](/img/trans.png)
[英]Spring boot, ElasticSearch and TestContainers integration tests. Connection refused
[英]Integration tests on spring-boot throws Connection refused
我對 Spring Boot 進行了單元測試:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class CustomerControllerIT {
private RestTemplate restTemplate = new RestTemplate();
@Test
public void findAllCustomers() throws Exception {
ResponseEntity<List<Customer>> responseEntity = restTemplate.exchange(
"http://localhost:8080/Customer", HttpMethod.GET, null,
new ParameterizedTypeReference<List<Customer>>() {
});
List<Customer> list = responseEntity.getBody();
Assert.assertEquals(list.size(), 0);
}
}
如果我在啟動的應用程序上啟動測試 - 測試正常
如果我嘗試僅啟動 IT,則會出現連接拒絕錯誤
我的application.properties
與單次啟動相同。
用於測試並位於資源和測試資源中。
Application.class 是:
@ComponentScan({"mypackage"})
@EntityScan(basePackages = {"mypackage.model"})
@EnableJpaRepositories(basePackages = {"mypackage.persistence"})
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
您必須使用正在運行的服務器運行測試,
如果您需要啟動一個完整運行的服務器,您可以使用隨機端口:
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
每次測試運行時都會隨機選擇一個可用端口
你需要這個 maven 依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
</dependency>
例子:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class TestRest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void findAllCustomers() throws Exception {
ResponseEntity<List<Customer>> responseEntity = restTemplate.exchange(
"/Customer", HttpMethod.GET, null,
new ParameterizedTypeReference<List<Customer>>(){});
List<Customer> list = responseEntity.getBody();
Assert.assertEquals(list.size(), 0);
}
}
請閱讀文檔以獲取更多參考
@SpringBootTest
,您可以使用:@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class MyUnitTests {
@Test
void checkActuator() throws Exception {
final String url = "http://localhost:8080/actuator/health";
@SuppressWarnings("rawtypes")
ResponseEntity<Map> re = new RestTemplate().getForEntity(url, Map.class);
System.out.println(re);
assertEquals(HttpStatus.OK, re.getStatusCode());
re.getStatusCode();
}
}
並將端口屬性添加到您的application.yml
(在文件夾src/main/resources
):
server:
port: 8080
或者如果有application.properties
:
server.port=8080
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.