Thursday, 27 November 2014

How to test file upload action in Play Framework 2 in Java?

In this post, we will see how we can test an action that expects a file upload (e.g. a profile picture or an image) in Play Framework 2 for Java. First, lets create an action that accepts a file upload as below:

 public static F.Promise uploadProfileImage() {
    final Http.MultipartFormData body = request().body().asMultipartFormData();
    final Http.MultipartFormData.FilePart picture = body.getFile("picture");
    User user = // get the user from db
    final File imgFile = picture.getFile();
    final String imgPathToSave = "images/" + "some unique name";
    //save on disk
    final boolean success = new File("images").mkdirs();
    final byte[] bytes = IOUtils.toByteArray(new FileInputStream(imgFile));
    FileUtils.writeByteArrayToFile(new File(imgPathToSave),bytes);
    user.profileImageUrl = imgPathToSave;;

AS you can see, the body of the request is a MultipartFormData. This makes a bit tricky to write functional tests in Play Framework 2 for Java actually. But, let's see the solution.

public void uploadProfileImageOK() throws Exception { 
   MultipartFormData.FilePart part = new MultipartFormData.FilePart<>("picture","test-image.jpg",Scala.Option("image/jpeg"),new File("test-image.jpg"));

   MultipartFormData formData = new MultipartFormData(Scala.>emptyMap(),Scala.toSeq(Arrays.asList(part)),Scala.emptySeq(),Scala. emptySeq());

   AnyContent anyContent = new AnyContentAsMultipartFormData(formData);

   Result uploadImageResult = callAction(controllers.routes.ref.UserController.uploadProfileImage(), fakeRequest().withHeader("Csrf-Token", "nocheck").withCookies(fakeCookie).withAnyContent(anyContent,"multipart/form-data", "POST"));

   assertEquals(OK, status(uploadImageResult));


To see more about functional testing in Play Framework 2 using Java see: How to test an action secure by SecureSocial in Play Framework 2 in Java

No comments:

Post a Comment