如下是SpringMvc项目里的Controller
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
/**
* @Author: daysurprise
* @Mote: 我于生命之中绽放, 犹如黎明中的花朵
* @Desc: 服务商充值上账web接口
*/
@Slf4j
@RestController
public class LevySeparateAccountingController {
/**
* 服务商充值上账回调
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/recharge/saveSyncReviewRecord.do", produces = "application/json;charset=UTF-8")
public String rechargeAccountingCallBack(HttpServletRequest request, HttpServletResponse response) {
response.setCharacterEncoding(ChannelConstant.CHARSET);
String reqData = request.getParameter("reqData");
log.info("###/rechargeAccountingCallBack 服务商充值上账回调加密参数:{}", reqData);
String returnMsg = "SUCCESS";
if (StringUtils.isEmpty(reqData)) {
returnMsg = "同步充值参数为空";
log.info("###/rechargeAccountingCallBack 服务商充值上账回调参数为空");
return returnMsg;
}
try {
...
} catch (ResponseException e) {
log.error("###/rechargeAccountingCallBack 服务商充值上账, {}", e.getMessage());
returnMsg = e.getMessage();
} catch (Exception e) {
log.error("###/rechargeAccountingCallBack 服务商充值上账回调异常:", e);
returnMsg = "ERROR:".concat(ExceptionUtils.getMessage(e));
}
return returnMsg;
}
}
重点来了,junit结合spring-test里的MockMvc来测试上面的http接口
package com.emax.channel.webapp.modules.levypay;
import com.emax.channel.webapp.BaseTest;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
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;
import java.util.List;
public class LevySeparateAccountingControllerTest extends BaseTest {
private final String secretKey = "DA17CC11D9A0F3FBC87A788036D260DF";
@Reference
private LevyMerchantRelationService levyMerchantRelationService;
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void testRechargeAccountingCallBack() throws Exception {
Result<List<LevyMerchantRelationDTO>> list = levyMerchantRelationService.list(new LevyMerchantRelationDTO());
LevyMerchantRelationDTO levyMerchantRelationDTO = list.getResult().get(0);
SeparateAccountingCallBackDto dto = JSON.parseObject(json, SeparateAccountingCallBackDto.class);
dto.setRechargeSource(RechargeSeparateModeEnum.OFFLINE_TRANSFER.getLevyValue());
dto.setAccountId(levyMerchantRelationDTO.getBankMerId());
dto.setAccName(levyMerchantRelationDTO.getMerName());
dto.setInterfaceKey(levyMerchantRelationDTO.getInterfaceKey());
String responseString = mockMvc
.perform(MockMvcRequestBuilders
.post("/recharge/saveSyncReviewRecord.do") //请求的url
.contentType(MediaType.APPLICATION_FORM_URLENCODED) //数据的格式
.param("reqData", AESUtil.encryptData(JSON.toJSONString(dto), secretKey)) //添加参数
)
.andExpect(MockMvcResultMatchers.status().isOk()) //返回的状态是200
.andDo(MockMvcResultHandlers.print()) //打印出请求和相应的内容
.andReturn()
.getResponse()
.getContentAsString();
System.out.println("----------------" + responseString);
}
}
运行结果(支持debug调试,是不是很爽):
2022-03-01 23:20:18.261[] [] [main] INFO o.s.b.test.mock.web.SpringBootMockServletContext:444 - Initializing Spring TestDispatcherServlet ''
2022-03-01 23:20:18.261[] [] [main] INFO o.s.test.web.servlet.TestDispatcherServlet:524 - Initializing Servlet ''
2022-03-01 23:20:18.304[] [] [main] INFO o.s.test.web.servlet.TestDispatcherServlet:546 - Completed initialization in 42 ms
2022-03-01 23:20:21.227[] [] [main] INFO c.e.c.w.m.levypay.LevySeparateAccountingController:65 - ###/rechargeAccountingCallBack 服务商充值上账回调加密参数:/30ypqDTqnRkYEpcDz+hq19pmk0EZp8z8NnM8d1ygPDRSReJ73fFxy8Yj/3+ ukvPrvSuzIcJH/nEMB9Fst842Sz....(900 chars)
MockHttpServletRequest:
HTTP Method = POST
Request URI = /recharge/saveSyncReviewRecord.do
Parameters = {reqData=[/30ypqDTqnRkYEpcDz+hq19pmk0EZp8z8NnM8d1ygPDRSReJ73fFxy8Yj/3+ ukvPrvSuzIcJH/nEMB9Fst842Szj5i2/X8ergNZU6UCSTBWK6T1Qa1UhZtVV x23hduXEmyNkkCUxGolfjYyxgEqVX+M5oawC72iIEByWqlWFlrsxTFQJgXAv VJ0DPGgWDSwtpU9xlqpOSJv5fkawMToA3e9ytzo8oWrXQxVgELPB9KosRKyM IsN11tGWclh+3RxWB023788MlHj48ljAAXK67HhJH4/GUVNb0nYvBhzG9f1d QWJuOWkGQrKgj0IQqc2+voqc8sPxQxB4cLxPSyDVtP+b1av8Hdl8FkWu5mf1 Cb5GmE9T3PJIGGv6D62QEyBoLvxgy/6zYYT4o2r7MkndxBoWIAJ3oZ3c+g2r t/x6XEgu7qNcTI+P5imy2VU0YjOb52Mvb8RRWUiNWmlqVhNWOXdyAC8380+H WGQrQ4MroHxOxTtYkdloPW6WWgCWlRjJQ+qiXiNvZc2UYizWN27ua4UDlt4J 5UNg5tjBFnabh/xcJj6nvdKUU4k+5J/SwG801hwfrtvm8VnLnu7/+4phm6E9 CpGKWDoVG83E07DNUnwS0KyC7nxUBvXxZuzLsWzT4+u8COtxHo9LWtbgtbgr R9ZnE4ahYjZuaePGiP4PtytmJT3TAU96s1fgdEK8O35n+tatKDZHv44peg6M 8SD9LzlGRfIbPcomuSP3VgMwfN/2STjTmnVyacTx1XpkyE2itbxrTW4ywJ7R BltFwmhS1SurXlEL2Vp1uB6SgAVeADFWXhoOanojVyTFX76+ySYg]}
Headers = [Content-Type:"application/x-www-form-urlencoded"]
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type = com.emax.channel.webapp.modules.levypay.LevySeparateAccountingController
Method = public java.lang.String com.emax.channel.webapp.modules.levypay.LevySeparateAccountingController.rechargeAccountingCallBack(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"7"]
Content type = application/json;charset=UTF-8
Body = SUCCESS
Forwarded URL = null
Redirected URL = null
Cookies = []
----------------SUCCESS
参考:
https://jfinal.com/feedback/2089