Use JSFUnit for testing of multipart/form-data file inputs

Tomahawk provides an t:inputFileUpload tag for uploading of files using <input type="file"/> element and multipart/form-data HTML form. Apparently I didn't found how to provide the value for the input element using JSFUnit API. But you can use an hook to the HtmlUnit to construct the upload request (see Using JSFUnit's RequestListenerfor more details about hook).

 

For example in your xhtml file you have tag:             

<t:inputFileUpload value="#{mybean.myFile}" id="uploadFile" required="false"
                                   binding="#{mybean.localcomponent"
                                   size="50"
                                   storage="file"
                        />

<t:commandButton id="uploadFileButton" action="#{mybean.doUpload}"/>

In your JSFUnit testcase you can use following:

 

public void testFileUpload(){

            component = server.findComponent("uploadFile");
            assertTrue(component.isRendered());
            assertTrue(component instanceof HtmlInputFileUpload);

            String fileToUpload = "/path/to/my/test/upload.file";
            component = server.findComponent("uploadFileButton");
            assertTrue(component.isRendered());
            WebClient webClient = wcSpec.getWebClient();
            JSFUnitWebConnection webConnection = (JSFUnitWebConnection) webClient.getWebConnection();

            MyRequestListener listener = new MyRequestListener(component.getId(),fileToUpload,"application/octet-stream","utf-8");
             webConnection.addListener(listener);
            client.click("uploadBundles");

}

 

    public class MyRequestListener implements RequestListener {
        private String charset;
        private String contentType;
        private String fileToUpload;
        private String componentId;
       
        public MyRequestListener(String componentId, String fileToUpload, String contentType,String charset){
            this.componentId = componentId;
            this.fileToUpload = fileToUpload;
            this.contentType = contentType;
            this.charset = charset;
        }
        public void beforeRequest(WebRequestSettings webRequestSettings) {
            List<NameValuePair> params = webRequestSettings.getRequestParameters();
            List<NameValuePair> newparams = new ArrayList<NameValuePair>(params.size());
            for (NameValuePair param : params) {
                if (param.getName().endsWith(componentId)) {

 

                    newparams
                            .add(new KeyDataPair(param.getName(), new File(fileToUpload), contentType, charset));
                } else {
                    newparams.add(param);
                }
            }
            webRequestSettings.setRequestParameters(newparams);
        }

 

        public void afterRequest(WebResponse webResponse) {

 

        }
    }