我有一个Resteasy webservice方法,它将MultipartFormDataInput对象作为其parm,并从中提取大量信息。我想为这个方法编写一个jUnit测试,但我一直无法找到任何方法来创建这个对象并在其中放入虚拟数据,因此我可以直接调用我的webservice方法。服务方法从这样的表单中提取数据......
@POST
@Path("/requestDeviceCode")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Consumes("multipart/form-data")
public DeviceCodeModel requestDeviceCode(final MultipartFormDataInput inputMultipart) {
// process the form data - only field in the form is the token
Map<String, List<InputPart>> formData = null; // we'll put the form data in here
formData = inputMultipart.getFormDataMap();
String token = null;
try {
token = formData.get("Token").get(0).getBodyAsString();
this._logger.debug("Pulled encrypted token out of input form, it's " + token);
并且工作正常,但尝试创建一个对象作为parm传递给'requestDeviceCode'让我受阻。我尝试过这种变化...
// create a multipartForm (input to the service POST) and add the "token" string to it
MultipartFormDataOutput newForm = new MultipartFormDataOutput();
newForm.addFormData("Token", encryptedXMLString, MediaType.APPLICATION_XML_TYPE);
_service.requestDeviceCode((MultipartFormDataInput) newForm);
但它只是没有这样做(这个特殊的错误是我无法将Output表单转换为Input表单)。我找不到创建新MultiPartFormDataInput并向其添加数据的方法。
有人有任何建议吗?
答案 0 :(得分:3)
在尝试对我的RestEasy WebService接受MultipartFormDataInput的方法进行单元测试时,我偶然发现了类似的问题。
您可以做的是模拟 MultipartFormDataInput ,为您希望接收的每个表单参数返回带有模拟 InputPart 的准备好的地图。
可能的解决方案(使用JUnit / Mockito):
@Test
public void testService() {
// given
MultipartFormDataInput newForm = mock(MultipartFormDataInput.class);
InputPart token = mock(InputPart.class);
Map<String, List<InputPart>> paramsMap = new HashMap<>();
paramsMap.put("Token", Arrays.asList(token));
when(newForm.getFormDataMap()).thenReturn(paramsMap);
when(token.getBodyAsString()).thenReturn("expected token param body");
// when
DeviceCodeModel actual = _service.requestDeviceCode(newForm);
// then
// verifications and assertions go here
}
答案 1 :(得分:0)
进行集成测试怎么样?
在测试中启动jetty或Tomcat,让它运行您的REST服务。
作为HTTP-Client,我将使用Apache HttpComponents Client,请参阅Tutorial上的examples page和MultiPart客户端示例。