1

我想对处理从 Web 表单上传的 Excel 工作表的 struts 操作设置单元测试。我选择了strutstest库并将其与cactus框架一起使用。Cactus 本身没有多部分请求选项。所以我又使用了一个库,并从仙人掌网站推荐了解决方法。

public class ActionTest extends CactusStrutsTestCase {

NVPair[] hdrs = new NVPair[1];
    //this method prepares request
public void beginFileUpload(WebRequest req) {
    NVPair[] opts = { new NVPair("MAX_FILE_SIZE", "20485760") };
    NVPair[] file = { new NVPair("myFile", "D://temp//TEST.xls") };     
    try {
        byte[] data = Codecs.mpFormDataEncode(opts, file, hdrs);
        InputStream i = new ByteArrayInputStream(data);
        req.setUserData(i);
        req.setContentType(hdrs[0].getValue());
        i.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

这里NVPairCodecs是推荐库中的类。当文件数据传递到服务器端的 apache POI 框架时,出现以下异常:

POIFSFileSystem poifs = new POIFSFileSystem(istTest);
...
java.io.IOException: Invalid header signature; read 0xC8001A0031006C00, expected 0xE11AB1A1E011CFD0

据我了解,文件数据已损坏,因为多部分请求未正确编码。我使用的文件格式很好。我使用apache commons httpclient库以不同的方式对其进行了测试:

   HttpClient httpclient = new DefaultHttpClient();
   try {
       HttpPost httppost = new HttpPost("http://localhost:9080" +
               "/retrieveData.do?background=yes");

       FileBody bin = new FileBody(new File("D://temp//TEST.xls"));

       //MultipartEntity reqEntity = new MultipartEntity(); this no param constructor also leads to exception 
       MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "47436622^%2824349", Charset.forName("ISO-8859-1"));
       reqEntity.addPart("bin", bin);
       httppost.setEntity(reqEntity);

       HttpResponse response = httpclient.execute(httppost);
       HttpEntity resEntity = response.getEntity();

       if (resEntity != null) {
           System.out.println("Response content length: " + resEntity.getContentLength());
       }
       EntityUtils.consume(resEntity);
   } finally {
       try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {}
   }

但是这种方法测试连接。我需要利用仙人掌来评估动作执行结果。任何建议表示赞赏!

4

0 回答 0