在Spring Boot Test測試程式可使用@LocalServerPort取得測試的web應用程式的port號。
範例環境:
- Java 1.8
- Spring Boot 2.2.1.RELEASE
例如下面是用來測試端點/hello的測試類別。應用程式的contextPath(環境路徑)為/demo。
DemoControllerTests
package com.abc.demo.controller;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class DemoControllerTests {
@LocalServerPort
private int port; // 注入port number
@Test
void hello_ReturnHello() throws Exception {
String url = "http://localhost:" + port + "/demo/hello"; // e.g. http://localhost:51667/demo/hello
// ...
}
}
@LocalServerPort其實相當於@Value("${local.server.port}")。
@Value("${local.server.port}")
private int port; // 注入port number
注意使用@LocalServerPort時必須是真實web環境,也就是@SpringBootTest的webEnvironment應為RANDOM_PORT或DEFINED_PORT。若為MOCK則mock web環境無法正確注入。
參考:
沒有留言:
張貼留言