Skip to content

Instantly share code, notes, and snippets.

@lin-zhao
Created April 4, 2014 23:40
Show Gist options
  • Save lin-zhao/9985191 to your computer and use it in GitHub Desktop.
Save lin-zhao/9985191 to your computer and use it in GitHub Desktop.
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.mock.*;
public class HTTPServiceTest {
/**
* Return a multipart/form-data MockHttpRequest
* @param parts Key is the name of the part, value is either a String or a File.
* @return
*/
private MockHttpRequest multipartRequest(String uri, Map parts) throws URISyntaxException, IOException {
MockHttpRequest req = MockHttpRequest.post(uri);
String boundary = UUID.randomUUID().toString();
req.contentType("multipart/form-data; boundary=" + boundary);
//Make sure this is deleted in afterTest()
File tmpMultipartFile = Files.createTempFile(null, null).toFile();
System.out.println("Tmp file:" + tmpMultipartFile.getAbsolutePath());
FileWriter fileWriter = new FileWriter(tmpMultipartFile);
fileWriter.append("--").append(boundary);
for(Map.Entry entry : parts.entrySet()) {
if(entry.getValue() instanceof String) {
fileWriter.append("\n");
fileWriter.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"").append("\n\n");
fileWriter.append(entry.getValue().toString()).append("\n");
fileWriter.append("--").append(boundary);
} else if(entry.getValue() instanceof File) {
fileWriter.append("\n");
File val = (File) entry.getValue();
fileWriter.append(String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"",
entry.getKey(), val.getName())).append("\n");
fileWriter.append("Content-Type: application/octet-stream").append("\n\n");
FileInputStream fis = new FileInputStream(val);
int b = fis.read();
while(b >= 0) {
fileWriter.write(b);
b = fis.read();
}
fileWriter.append("\n").append("--").append(boundary);
}
}
fileWriter.append("--");
fileWriter.flush();
fileWriter.close();
req.setInputStream(new FileInputStream(tmpMultipartFile));
return req;
}
public void testSomething() {
Map parts = new HashMap();
parts.put("foo1", "bar1");
parts.put("foo2", "bar2");
parts.put("aFile", new File("path-to-file"));
MockHttpRequest request = multipartRequest("/path/to/service", parts);
MockHttpResponse response = new MockHttpResponse();
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addSingletonResource(new MyHTTPService());
dispatcher.invoke(request, response);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment