一.Service層單元測試:web
代碼以下:spring
package com.dudu.service;
import com.dudu.domain.LearnResource;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.hamcrest.CoreMatchers.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class LearnServiceTest {
@Autowired
private LearnService learnService;
@Test
public void getLearn(){
LearnResource learnResource=learnService.selectByKey(1001L);
Assert.assertThat(learnResource.getAuthor(),is("博客園"));
}
}
就是最簡單的單元測試寫法,頂部只要和便可,想要執行的時候,鼠標放在對應的方法,右鍵選擇run該方法便可。
@RunWith(SpringRunner.class)SpringBootTest
二.Controller層單元測試json
Controller類:session
package com.dudu.controller;
/**
* 教程頁面
*/
@Controller
@RequestMapping("/learn")
public class LearnController extends AbstractController{
@Autowired
private LearnService learnService;
private Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping("")
public String learn(Model model){
model.addAttribute("ctx", getContextPath()+"/");
return "learn-resource";
}
/**
* 查詢教程列表
* @param page
* @return
*/
@RequestMapping(value = "/queryLeanList",method = RequestMethod.POST)
@ResponseBody
public AjaxObject queryLearnList(Page<LeanQueryLeanListReq> page){
List<LearnResource> learnList=learnService.queryLearnResouceList(page);
PageInfo<LearnResource> pageInfo =new PageInfo<LearnResource>(learnList);
return AjaxObject.ok().put("page", pageInfo);
}
/**
* 新添教程
* @param learn
*/
@RequestMapping(value = "/add",method = RequestMethod.POST)
@ResponseBody
public AjaxObject addLearn(@RequestBody LearnResource learn){
learnService.save(learn);
return AjaxObject.ok();
}
/**
* 修改教程
* @param learn
*/
@RequestMapping(value = "/update",method = RequestMethod.POST)
@ResponseBody
public AjaxObject updateLearn(@RequestBody LearnResource learn){
learnService.updateNotNull(learn);
return AjaxObject.ok();
}
/**
* 刪除教程
* @param ids
*/
@RequestMapping(value="/delete",method = RequestMethod.POST)
@ResponseBody
public AjaxObject deleteLearn(@RequestBody Long[] ids){
learnService.deleteBatch(ids);
return AjaxObject.ok();
}
/**
* 獲取教程
* @param id
*/
@RequestMapping(value="/resource/{id}",method = RequestMethod.GET)
@ResponseBody
public LearnResource qryLearn(@PathVariable(value = "id") Long id){
LearnResource lean= learnService.selectByKey(id);
return lean;
}
}
Controller的測試類:
代碼以下:
package com.dudu.controller;
import com.dudu.domain.User;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
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;
@RunWith(SpringRunner.class)
@SpringBootTest
public class LearnControllerTest {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
private MockHttpSession session;
@Before
public void setupMockMvc(){
mvc = MockMvcBuilders.webAppContextSetup(wac).build(); //初始化MockMvc對象
session = new MockHttpSession();
User user =new User("root","root");
session.setAttribute("user",user); //攔截器那邊會判斷用戶是否登陸,因此這裏注入一個用戶
}
/**
* 新增教程測試用例
* @throws Exception
*/
@Test
public void addLearn() throws Exception{
String json="{\"author\":\"HAHAHAA\",\"title\":\"Spring\",\"url\":\"http://tengj.top/\"}";
mvc.perform(MockMvcRequestBuilders.post("/learn/add")
.accept(MediaType.APPLICATION_JSON_UTF8)
.content(json.getBytes()) //傳json參數
.session(session)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
/**
* 獲取教程測試用例
* @throws Exception
*/
@Test
public void qryLearn() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/learn/resource/1001")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_JSON_UTF8)
.session(session)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.author").value("嘟嘟MD獨立博客"))
.andExpect(MockMvcResultMatchers.jsonPath("$.title").value("Spring Boot乾貨系列"))
.andDo(MockMvcResultHandlers.print());
}
/**
* 修改教程測試用例
* @throws Exception
*/
@Test
public void updateLearn() throws Exception{
String json="{\"author\":\"測試修改\",\"id\":1031,\"title\":\"Spring Boot乾貨系列\",\"url\":\"http://tengj.top/\"}";
mvc.perform(MockMvcRequestBuilders.post("/learn/update")
.accept(MediaType.APPLICATION_JSON_UTF8)
.content(json.getBytes())//傳json參數
.session(session)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
/**
* 刪除教程測試用例
* @throws Exception
*/
@Test
public void deleteLearn() throws Exception{
String json="[1031]";
mvc.perform(MockMvcRequestBuilders.post("/learn/delete")
.accept(MediaType.APPLICATION_JSON_UTF8)
.content(json.getBytes())//傳json參數
.session(session)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
}
三.新斷言assertThat使用mvc
基本語法:assertThat( [value], [matcher statement] );
- value 是接下來想要測試的變量值;
- matcher statement 是使用 Hamcrest 匹配符來表達的對前面變量所指望的值的聲明,若是 value 值與 matcher statement 所表達的指望值相符,則測試成功,不然測試失敗
使用例子:app
字符相關匹配符
/**equalTo匹配符斷言被測的testedValue等於expectedValue,
* equalTo能夠斷言數值之間,字符串之間和對象之間是否相等,至關於Object的equals方法
*/
assertThat(testedValue, equalTo(expectedValue));
/**equalToIgnoringCase匹配符斷言被測的字符串testedString
*在忽略大小寫的狀況下等於expectedString
*/
assertThat(testedString, equalToIgnoringCase(expectedString));
/**equalToIgnoringWhiteSpace匹配符斷言被測的字符串testedString
*在忽略頭尾的任意個空格的狀況下等於expectedString,
*注意:字符串中的空格不能被忽略
*/
assertThat(testedString, equalToIgnoringWhiteSpace(expectedString);
/**containsString匹配符斷言被測的字符串testedString包含子字符串subString**/
assertThat(testedString, containsString(subString) );
/**endsWith匹配符斷言被測的字符串testedString以子字符串suffix結尾*/
assertThat(testedString, endsWith(suffix));
/**startsWith匹配符斷言被測的字符串testedString以子字符串prefix開始*/
assertThat(testedString, startsWith(prefix));
通常匹配符
/**nullValue()匹配符斷言被測object的值爲null*/
assertThat(object,nullValue());
/**notNullValue()匹配符斷言被測object的值不爲null*/
assertThat(object,notNullValue());
/**is匹配符斷言被測的object等於後面給出匹配表達式*/
assertThat(testedString, is(equalTo(expectedValue)));
/**is匹配符簡寫應用之一,is(equalTo(x))的簡寫,斷言testedValue等於expectedValue*/
assertThat(testedValue, is(expectedValue));
/**is匹配符簡寫應用之二,is(instanceOf(SomeClass.class))的簡寫,
*斷言testedObject爲Cheddar的實例
*/
assertThat(testedObject, is(Cheddar.class));
/**not匹配符和is匹配符正好相反,斷言被測的object不等於後面給出的object*/
assertThat(testedString, not(expectedString));
/**allOf匹配符斷言符合全部條件,至關於「與」(&&)*/
assertThat(testedNumber, allOf( greaterThan(8), lessThan(16) ) );
/**anyOf匹配符斷言符合條件之一,至關於「或」(||)*/
assertThat(testedNumber, anyOf( greaterThan(16), lessThan(8) ) );
數值相關匹配符
/**closeTo匹配符斷言被測的浮點型數testedDouble在20.0¡À0.5範圍以內*/
assertThat(testedDouble, closeTo( 20.0, 0.5 ));
/**greaterThan匹配符斷言被測的數值testedNumber大於16.0*/
assertThat(testedNumber, greaterThan(16.0));
/** lessThan匹配符斷言被測的數值testedNumber小於16.0*/
assertThat(testedNumber, lessThan (16.0));
/** greaterThanOrEqualTo匹配符斷言被測的數值testedNumber大於等於16.0*/
assertThat(testedNumber, greaterThanOrEqualTo (16.0));
/** lessThanOrEqualTo匹配符斷言被測的testedNumber小於等於16.0*/
assertThat(testedNumber, lessThanOrEqualTo (16.0));
集合相關匹配符
/**hasEntry匹配符斷言被測的Map對象mapObject含有一個鍵值爲"key"對應元素值爲"value"的Entry項*/
assertThat(mapObject, hasEntry("key", "value" ) );
/**hasItem匹配符代表被測的迭代對象iterableObject含有元素element項則測試經過*/
assertThat(iterableObject, hasItem (element));
/** hasKey匹配符斷言被測的Map對象mapObject含有鍵值「key」*/
assertThat(mapObject, hasKey ("key"));
/** hasValue匹配符斷言被測的Map對象mapObject含有元素值value*/
assertThat(mapObject, hasValue(value));