使用Spring Boot REST API進行測試驅動開發
Maven外掛rest-assured 是Java DSL測試REST服務,這個外掛需要groovy-all來執行測試。
我們將新增maven-failsafe-plugin外掛來執行整合測試:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <executions> <execution> <id>integration-test</id> <goals> <goal>integration-test</goal> </goals> </execution> <execution> <id>verify</id> <phase>verify</phase> <goals> <goal>verify</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <id>pre-integration-test</id> <goals> <goal>start</goal> </goals> </execution> <execution> <id>post-integration-test</id> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
測試類程式碼如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class)
@TestPropertySource(value={"classpath:application.properties"})
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
public class SpringRestControllerTest {
@Value("${server.port}")
int port;
@Test
public void getDataTest() {
get("/api/tdd/responseData").then().assertThat().body("data", equalTo("responseData"));
}
@Before
public void setBaseUri () {
RestAssured.port = port;
RestAssured.baseURI = "http://localhost"; // replace as appropriate
}
}
@RunWith(SpringJUnit4ClassRunner.class)支援載入Spring應用程式上下文。
@ContextConfiguration定義類級元資料,用於確定如何為整合測試載入和配置ApplicationContext。
@TestPropertySource用於配置屬性檔案的位置。
@SpringBootTest告訴Spring Boot去尋找一個主配置類(例如,一個帶有@SpringBootApplication的類)並使用它來啟動Spring應用程式上下文。
由於我們尚未定義REST端點,因此我們可以使用該mvn verify 命令執行上述測試以檢視測試失敗。
讓我們通過引入REST控制器來修復我們的測試:
@RestController
public class SpringRestController {
@RequestMapping(path = "/api/tdd/{data}", method= RequestMethod.GET)
public Response getData(@PathVariable("data") String data) {
return new Response(data);
}
//inner class
class Response {
private String data;
public Response(String data) {
this.data = data;
}
public String getData() {
return data;
}
}
}
在上面的類中,我們有一個REST端點,它接受“data”作為輸入,並在響應體中返回一個新的“Response”例項。
讓我們mvn verify 再次執行命令。它現在應該成功執行測試。