簡單記錄在Spring Boot 2.x對掛有@RestController
的Controller的方法以JUnit 5進行單元測試。
Spring Boot的application.properties
配置檔設定了Servlet環境根目錄為/mydemo
。
application.properties
#context
server.servlet.context-path=/mydemo
server.port=8080
被測試的Controller類別
DemoController
package com.abc.demo.controller;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
@GetMapping(path="/get")
public String getDemo() {
return "hello world";
}
@GetMapping(path="/get/user", produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
public String getJsonDemo() {
return "{\"name\":\"john\"}";
}
}
負責測試DemoController
的測試類別,要在類別上掛@AutoConfigureMockMvc
,並@Autowired
注入MockMvc
來模擬Request的發送。
被測試的DemoController.getDemo()
方法的完整url路徑為localhost:8080/mydemo/get
,但在MockMvcRequestBuilders.get(String urlTemplate, Object... uriVars)
的url參數urlTemplate
只要從環境根目錄後開始寫,所以為"/get"
。
DemoControllerTest
package com.abc.demo.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
public class DemoControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void testGetDemo() throws Exception {
mvc.perform(get("/get"))
.andExpect(status().isOk())
.andExpect(content().string("hello world"));
}
@Test
public void testGetJsonDemo() throws Exception {
mvc.perform(get("/get/user"))
.andExpect(status().isOk())
.andExpect(content().json("{\"name\":\"john\"}"));
}
}
參考:
沒有留言:
張貼留言