java - Test MultipartFormData in Play 2.0 FakeRequest -
i'm trying create function test play 2 controller takes multipart form data input. there no method in fakerequest support multipart form post. other ways test controller?
map<string, object> map = new hashmap<string, object>(); map.put("param1", "test-1"); map.put("param2", "test-2"); map.put("file", file) result result = routeandcall(fakerequest(post, "/register").withformurlencodedbody(map));// no such method edit: workaround did test multipart.
httpclient httpclient = new defaulthttpclient(); httppost httppost = new httppost("http://localhost:3333/blobupload"); filebody imagefile = new filebody(new file("test/resources/test-1.jpg")); stringbody guid1 = null; stringbody guid2 = null; try { guid1 = new stringbody("guid-1"); } catch (unsupportedencodingexception e1) { e1.printstacktrace(); } multipartentity reqentity = new multipartentity(); reqentity.addpart("key1", imagefile); reqentity.addpart("key2", guid1); httppost.setentity(reqentity); httpresponse response; try { response = httpclient.execute(httppost); httpentity resentity = response.getentity(); assertthat(response.getstatusline().getstatuscode()).isequalto(200); } catch (clientprotocolexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); }
you should use callaction use withformurlencodedbody
@test public void testmyaction() { running(fakeapplication(), new runnable() { public void run() { map<string,string> data = new hashmap<string, object>(); data.put("param1", "test-1"); data.put("param2", "test-2"); data.put("file", file); result result = callaction( controllers.whatever.action(), fakerequest().withformurlencodedbody(data) ) ... } } } i use scala api play framework 2 dont think can test multipart form using withformurlencodedbody.
you can in way in scala:
import play.api.libs.files._ import play.api.mvc.multipartformdata._ class mytestspec extends specification { "mytest should bla bla bla" in { running(fakeapplication(aditionalconfiguration = inmemorydatabase())) { val data = new multipartformdata(map( ("param1" -> seq("test-1")), ("param2" -> seq("test-2")) ), list( filepart("payload", "message", some("content-type: multipart/form-data"), play.api.libs.files.temporaryfile(new java.io.file("/tmp/pepe.txt"))) ), list(), list()) val some(result) = routeandcall(fakerequest(post, "/route/action", fakeheaders(), data)) ... } } } i guess can translate java, don't know how code in java sorry.
p.d: sorry english i'm still learning
Comments
Post a Comment