2012-04-17 118 views
3

我想在我的应用程序中测试文件上传。上传本身按部分中所述的方式进行处理。直接文件上传http://www.playframework.org/documentation/2.0/JavaFileUpload上。测试AJAX文件上传

我使用的是最新的Play20版本,并按here所述构建。

我当前的代码看起来是这样,但显然部分缺失增加了一个测试文件的要求:

Test.java

FakeRequest request = fakeRequest(POST, "/measurement/123/file"); 
// how to append test file to this request?  
Result result = routeAndCall(request); 
assertOK(result); 

Controller.java

public static uploadFile() { 
    RequestBody body = request().body(); 
    if (body != null) { 
     RawBuffer rawBuffer = body.asRaw(); 
     if (rawBuffer != null) { 
      File uploadedFile = rawBuffer.asFile(); 
      // ... 
     } 
    } 
    return ok(); 
} 

回答

0

根据source code,FakeRequest呼叫的签名是:

case class FakeRequest[A](method: String, uri: String, headers: FakeHeaders, body: A) extends Request[A] 

你应该能够检查将文件上载到应用程序中的POST请求的主体和复制体在您的测试代码的参数。另一种方法是在多部分POST上根据RFC description构建它。

+0

你可以举一个例子如何做到这一点? – pangratz 2012-04-18 10:21:18

1

我对Play 2 Java文件上传测试的解决方案是创建一个UploadFakeRequest扩展FakeRequest。在课堂内部,我有我自己withRawBody方法与类似的东西:

RawBuffer raw = new RawBuffer(1000, data.getBytes()); // No clue what is the correct value here... 
AnyContentAsRaw content = new AnyContentAsRaw(raw); 
fake = new play.api.test.FakeRequest(POST, fake.path(), new play.api.test.FakeHeaders(Scala.asScala(map)), content, "127.0.0.1"); 
+0

谢谢,这看起来很有希望。我会试试看... – pangratz 2012-12-04 11:02:45