轉載註明出處:http://www.cnblogs.com/wade-xu/p/4311205.html html
接我前面一篇文章關於RestAssured測試Restful web service的, RestAssured還有一個功能, 使用RestAssuredMockMvc 單元測試你的Spring MVC Controllers, 這個MockMvc 是創建在Spring MockMvc基礎上的, 其目的是讓咱們用起來更便捷。web
<dependency> <groupId>com.jayway.restassured</groupId> <artifactId>spring-mock-mvc</artifactId> <version>2.4.0</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- Optional --> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> <version>1.3</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-library</artifactId> <version>1.3</version> <scope>test</scope> </dependency>
下面是咱們要測試的Controllerspring
package com.wadeshop.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class GreetingController { private static final String template = "Hello, %s!"; @RequestMapping(value = "/greeting", method = RequestMethod.GET) @ResponseBody public Greeting greeting(@RequestParam(value="name", required=false, defaultValue="World") String name) { return new Greeting(String.format(template, name)); } }
Greeting 類 以下mvc
public class Greeting { private final String content; public String getContent() { return content; } public Greeting(String content) { this.content = content; } }
##轉載註明出處:http://www.cnblogs.com/wade-xu/p/4311205.html app
接下來就是建立Spring MVC 測試類了單元測試
package com.wadeshop.controller; import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.given; import static org.hamcrest.Matchers.equalTo; import org.junit.Before; import org.junit.Test; import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc; public class GreetingControllerTest { @Before public void configured() { RestAssuredMockMvc.standaloneSetup(new GreetingController()); } @Test public void test1() { given(). param("name", "Johan"). when(). get("/greeting"). then(). statusCode(200). body("content", equalTo("Hello, Johan!")); } @Test public void test2() { given(). param("name", ""). when(). get("/greeting"). then(). statusCode(200). body("content", equalTo("Hello, World!")); } }
單元測試過程無非就這些步驟:測試
1. 準備測試環境, 上面的例子就是使用 standalone setup 初始化MockMvc, 傳入被測Controllerui
2. 傳入參數構造請求而且調用this
3. 驗證結果google
執行結果以下
是否是很簡單?
這種方式其實就是純粹的單元測試,若是想模擬真實的Spring MVC, 走Spring MVC完整流程,好比Dispatcher servlet, 類型轉換,數據綁定等等, 則須要用MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); 我在之後的文章中會介紹到。
https://code.google.com/p/rest-assured/wiki/Usage#Spring_Mock_Mvc_Module