JUnit 單元測試-Controller
1.GET請求
1.1 演示介面
@Controller
@RequestMapping(value = "/hello")
public class HelloController {
@GetMapping("/test")
@ResponseBody
public Map<String, String> test() {
return Collections.singletonMap("message", "Hello");
}
}
響應:
{
"message": "Hello"
}
1.2 測試用例
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.Rollback;
import org.springframework .test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework .test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.hamcrest.core.Is.is;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
/**
* @Author : xiao
* @Date : 17/5/9 下午2:16
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-mvc.xml", "classpath:spring/spring-mybatis.xml"})
//當然 你可以宣告一個事務管理 每個單元測試都進行事務回滾 無論成功與否
@Rollback
public class HelloControllerTest {
private static final Logger logger = LoggerFactory.getLogger(HelloControllerTest.class);
private MockMvc mockMvc;
@Autowired
WebApplicationContext webApplicationContext;
@Before
public void setUp(){
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void testStatus() throws Exception {
String url = "/hello/test";
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get(url)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
}
@Test
public void testMessage() throws Exception {
String url = "/hello/test";
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get(url)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(jsonPath("$.message", is("Hello")))
.andDo(MockMvcResultHandlers.print())
.andReturn();
}
}
2. Post請求測試
2.1 請求介面
@PostMapping("/user")
@ResponseBody
public String pstUser(@RequestBody UserVO userVO) {
logger.info(userVO.toString());
return CommonResult.success(userVO).toJSON();
}
請求地址:
請求引數:
{
"name": "xiao",
"age":21,
"address":"asfasdfasdfasdf.adsfa.asdf"
}
響應:
{
"data": {
"address": "asfasdfasdfasdf.adsfa.asdf",
"age": 21,
"name": "xiao"
},
"message": "成功",
"status": 1
}
2.2 單元測試
@Test
public void testUser() throws Exception {
String url = "/hello/user";
UserVO userVO = new UserVO();
userVO.setName("xiao");
userVO.setAge(12);
userVO.setAddress("asdf.asdfasdf.asdfasd");
String requestJson = JSONObject.toJSONString(userVO);
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(url)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(requestJson.getBytes())
.accept(MediaType.APPLICATION_JSON)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(jsonPath("$.status", is(1)))
.andExpect(jsonPath("$.message", is("成功")))
.andDo(MockMvcResultHandlers.print())
.andReturn();
}
3.常見錯誤
3.1 EL表示式錯誤
Unable to load 'javax.el.ExpressionFactory'. Check that you have the EL dependencies on the classpath, or use ParameterMessageInterpolator instead
pom.xml檔案新增依賴:
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.0</version>
<scope>test</scope>
</dependency>
3.2 javax.servlet.http.HttpServletRequest 方法找不到
java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.isAsyncStarted()
是由於 servlet-api版本引起的:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>test</scope>
</dependency>
3.3 Predicate 類沒有找到
java.lang.NoClassDefFoundError: com/jayway/jsonpath/Predicate
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
<scope>test</scope>
</dependency>
相關推薦
Spring mvc 之Junit 單元測試 Controller中方法
Springmvc 之Junit 單元測試 1. 首先引入測試的jar包。 1.1因為我用的ide是eclipse,現只介紹eclipse中junit的使用。首先引用eclipse中自帶的junit, 方法: 右鍵專案—>proper
JUnit 單元測試-Controller
1.GET請求 1.1 演示介面 @Controller @RequestMapping(value = "/hello") public class HelloController { @GetMapping("/test") @Re
SpringBoot專案,使用MockMvc做controller類的JUNIT單元測試
package hello; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.t
Spring對Controller、Service、Dao進行Junit單元測試總結
Spring對Controller、Service、Dao進行Junit單元測試總結 [email protected]事務控制,避免資料庫出現髒資料(若要提交到資料庫,先注掉) 2.hibernate配置檔案 <property name="defaultAutoComm
【Android進階】Junit單元測試環境搭建以及簡單有用
rar theme 選擇 http 技術分享 才幹 ack package family 單元測試的目的 首先。Junit單元測試要實現的功能,就是用來測試寫好的方法是否可以正確的運行,一般多用於對業務方法的測試。 單元測試的環境配置 1.在Andro
Java Junit單元測試步驟總結
logs 其他 同時 new 技術 src eclipse test 分享 哎呀,莫名其妙已經半夜12點了。總結的如有錯誤的地方歡迎指正,我的這個方法沒有引入jar,網上有其他引入jar包的方法,不是很懂,也沒有太怎麽看。 關鍵的一些基本規則: 下面我們來看Eclipse
備忘:Junit單元測試
環境 包名 args 方法 成功 junit單元測試 備忘 [] 命名 junit 目前測試都是在main方法中調用目前的結果都需要人工對比是否是想要的 1.使用Junit測試方法,綠色條條代表方法測試成功,沒有bug,如果是紅色條條代表有異常,測試不通過2.點擊方法名、類
Junit單元測試
ora final類 state isalive -s 查詢 string 順序 new LLT是測試系統的一部分,主要是由代碼開發人員來編寫,Mock的意思是效仿模仿的意思,就是最測試過程中不需要的一些類和方法模擬出相應的返回值,稱為打樁,測試關註的是一個類或
Junit單元測試學習筆記
顯示 ima add return 手寫 style 創建 spring 編寫 軟件開發的過程中,測試環節是少不了的,如果沒有測試,軟件的質量難以保證。但是如果用main函數手寫log的方式進行測試顯得過於繁瑣,也不方便一次性測試多個模塊,效率低。 因此需要我們
Junit 單元測試在 intelliJ IDEA 中的安裝
repo setting 進入 安裝 junit sta rain pos 每次 1.為什麽使用Junit我們都知道,main 方法是一個程序的入口,通常來說,沒有main方法,程序就無法運行。我們經常會寫一些class文件(如下圖所示),他們並沒有自己的main方法。那麽
Junit單元測試遇到的initializationerror:method initializationerror not found
測試 ner erro err 分享圖片 除了 junit rar 必須 原因可能如下: 1.有返回值的方法不能直接測試 2.帶參數的方法不能直接測試 3.訪問權限在public一下的方法不能直接測試 4.static靜態方法不能直接測試 5.不能給出現前四個條件中任意一
配置junit單元測試
bsp group junit單元測試 test pen 單元 配置 artifact 測試 <properties> <junit.version>4.12</junit.version> </propertie
JUnit 單元測試
eas 禁用 not 支付 true 通過 char 建立 功能 (1)什麽是測試? TDD TDD是測試編程驅動,編程方法學, 也是一種編程思想,是先寫測試用例再編碼。 特點是:保證了代碼的質量,測試的覆蓋率高, 但是開發效率低。 DDD 領域驅動設計 測試本身也是一
junit單元測試注意的問題
1.有返回值的方法不能直接測試2.帶引數的方法不能直接測試3.訪問許可權在public一下的方法不能直接測試4.static靜態方法不能直接測試5.不能給出現前四個條件中任意一個的方法新增@Test註解,否則執行滿足@Test條件的方法也會出現initializationerror初始化異常---------
Spring Boot Junit單元測試
摘要: Junit這種老技術,現在又拿出來說,不為別的,某種程度上來說,更是為了要說明它在專案中的重要性。 憑本人的感覺和經驗來說,在專案中完全按標準都寫Junit用例覆蓋大部分業務程式碼的,應該不會超過一半。 剛好前段時間寫了一些關於SpringBoot的帖子,正好現在把Junit再拿
springBoot dubbo junit 單元測試
依賴 <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version> 4.12</versi
使用MockMvc進行Junit單元測試
一、單元測試的目的 簡單來說就是在我們增加或者改動一些程式碼以後對所有邏輯的一個檢測,尤其是在我們後期修改後(不論是增加新功能,修改bug),都可以做到重新測試的工作。以減少我們在釋出的時候出現更過甚至是出現之前解決了的問題再次重現。 這裡主要是使用MockMvc對我們
SSH框架JUnit單元測試遇到的Bug
問題描述 專案框架使用SpringMVC&Spring&MyBatis框架開發,在tomcat容器中執行正常,但是使用JUnit對DAO層進行單元測試出現BindingException,異常日誌: org.apache.ibatis.binding.BindingE
Junit 單元測試@Test註解的方法報錯Annotations are not allowed here
問題描述: Annotations are not allowed here 使用IDEA開發的時候,單元測試如果不使用IDE提供的方式建立,而是自己手動建立的話,會報這
java-junit單元測試工具
java-junit單元測試工具 Junit下載地址:http://pan.baidu.com/s/1eQfQQw6 優點: 1.不用寫把方法寫main函式裡面進行測試。 2.不用進行人工對比。 操作: 1.匯入juni