1. 程式人生 > 其它 >Spring Boot Junit4單元測試MockMvc的使用

Spring Boot Junit4單元測試MockMvc的使用

1.Controller程式碼如下:

@RestController
@RequestMapping("/vss")
@Api(value = "usermanagement parameter",description = "usermanagement controller interface")
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);

@Autowired
private RoleService roleService;

@Autowired
private UserService userService;

@Autowired
private OperatorService operatorService;

@Autowired
private SystemParameterService systemParameterService;

@GetMapping("/user/getUserInfoByPage")
@ApiOperation(value = "get user data by page", notes = "show user data by pagination parameter")
public ResultBean getUserInfoByPage(@RequestParam("index")int pageIndex,@RequestParam("size")int pageSize){
ResultBean resultBean=new ResultBean();
try{
resultBean.setData(userService.getUserByPage(pageIndex,pageSize));
}catch (Exception e){
resultBean.setCode(ResponseCodeType.FAULT.getCode());
resultBean.setMessage(ResponseCodeType.FAULT.getCodeDescription());
logger.error("user controller exception",e);
}
return resultBean;
}
@PostMapping("/operator/delete/{operatorId}")
@ApiOperation(value = "delete operator by id ", notes = "delete operator by id")
@Transactional(rollbackOn = Exception.class)
public ResultBean deleteOperator(@PathVariable("operatorId") long operatorId){
ResultBean resultBean=new ResultBean();
try {
operatorService.deleteOperator(operatorId);
}catch (Exception e){
resultBean.setCode(ResponseCodeType.FAULT.getCode());
resultBean.setMessage(ResponseCodeType.FAULT.getCodeDescription());
logger.error("delete operator interface happen error",e);
}
return resultBean;
}
@PostMapping("/opeartor/save")
@ApiOperation(value="save opeartor ", notes="save opeartor")
public ResultBean saveOperator(@RequestBody RequestOperatorData requestOperatorData){
ResultBean resultBean=new ResultBean();
try{
boolean saveOperatorResult= operatorService.saveOperator(requestOperatorData);
if(!saveOperatorResult){
resultBean.setCode(ResponseCodeType.WARNING.getCode());;
resultBean.setMessage("operator name has exists!");
logger.debug("operator name has exists.roleName:{}",requestOperatorData.getOperatorName());
}
}catch(Exception e){
resultBean.setCode(ResponseCodeType.FAULT.getCode());
resultBean.setMessage(ResponseCodeType.FAULT.getCodeDescription());
logger.error("save operator interface happen error",e);
}
return resultBean;
}

2.Test程式碼:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {

//啟用Web上下文
@Autowired
private WebApplicationContext webApplicationContext;

private MockMvc mockMvc ;

@Before
public void setUp() throws Exception {
// mockMvc = MockMvcBuilders.standaloneSetup(new UserController()).build();
//使用上下文構建MockMvc
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

@After
public void tearDown() throws Exception {
}


@Test
public void getUserInfoByPage() throws Exception{
//執行請求(使用GET請求)
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/vss/user/getUserInfoByPage").param("index","1").param("size","10") //若無引數則不寫param.
.accept(MediaType.APPLICATION_JSON_UTF8)).andReturn();
//獲取返回編碼
int status = mvcResult.getResponse().getStatus();
//獲取返回結果
String content = mvcResult.getResponse().getContentAsString();
//斷言,判斷返回編碼是否正確
Assert.assertEquals(200,status);
System.out.println("--------返回的json = " + content);
}

@Test
public void operatorDelete() throws Exception{
//執行請求(使用POST請求)
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/vss/operator/delete/{operatorId}",1).accept(MediaType.APPLICATION_JSON_UTF8)).andReturn();

//獲取返回編碼
int status = mvcResult.getResponse().getStatus();
//獲取返回結果
String content = mvcResult.getResponse().getContentAsString();
//斷言,判斷返回編碼是否正確
Assert.assertEquals(200,status);
}


@Test
public void opeartorSave() throws Exception{
//多個引數的傳遞
OperatorEntity operatorEntity=new OperatorEntity();
//建立新使用者
RequestOperatorData requestOperatorData = new RequestOperatorData();
requestOperatorData.setCreatedBy("admin");
requestOperatorData.setOperatorId(1);
requestOperatorData.setOperatorName("test");
requestOperatorData.setOperatorType("1");
requestOperatorData.setUpdatedBy("admin");

//將引數轉換成JSON物件
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(requestOperatorData);


//執行請求(使用POST請求,傳遞多個引數)
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/vss/opeartor/save").content(json).contentType(MediaType.APPLICATION_JSON)).andReturn();
//獲取返回編碼
int status = mvcResult.getResponse().getStatus();
//獲取返回結果
String content = mvcResult.getResponse().getContentAsString();


//斷言,判斷返回編碼是否正確
assertEquals(200,status);
}