简体   繁体   中英

How to make SlingHttpServletRequest.getParts() return the proper value in JUnit Test?

I am facing some difficulties in writing junit test to pass the for loop condition to getParts() method from SlingHttpServletRequest.getParts(). There is no problem with the implementation, I am able to process the file attachment properly. However, I am unable to do so in the junit test.

The following is my implementation:

@Model(adaptables = SlingHttpServletRequest.class)
public class Comment {

    //Variables declaration

    @Inject
    private CommentService service;

    @PostConstruct
    public void setup() {
        requestData = new JSONObject();


        for (String item : request.getRequestParameterMap().keySet()) {

            try {
                    requestData.put(item, request.getParameter(item));
                }
            } catch (Exception e) {
                Throw error message
            }
        }

        //Upload attachment to server
        try {
            for (Part part : request.getParts()) {      <= The JUnit test stopped at this line and throw the error below

        } catch (Exception e) {
            Throw error message
        }

I have tried using a SlingHttpServletRequestWrapper class to override the getParts method but to no avail.

The following is my junit test:

public class CommentTest {

    public final AemContext context = new AemContext();
    private CommentService commentService = mock(CommentService.class);

    @InjectMocks
    private Comment comment;

    private static String PATH = "/content/testproject/en/page/sub-page";

    @Before
    public void setUp() throws Exception {
        context.addModelsForPackage("de.com.adsl.sightly.model");
        context.load().json("/components/textrte.json", PATH);
        context.currentPage(PATH);
    }

    @Test
    public void testSetup() throws IOException, ServletException {
        //before
        context.request().setParameterMap(getRequestCat1());
        context.registerService(CommentService.class, commentService);

        Resource resource = context.resourceResolver().getResource(PATH + "/jcr:content/root/responsivegrid/textrte");
        assertNotNull(resource);

        //when
        comment = new CustomRequest(context.request()).adaptTo(Comment.class);

        //then
        comment.setup();

    }

    private class CustomRequest extends SlingHttpServletRequestWrapper {

        public CustomRequest(SlingHttpServletRequest request) {
            super(request);
        }

        @Override
        public Collection<Part> getParts() {
            final String mockContent =
                    "------WebKitFormBoundarycTqA2AimXQHBAJbZ\n" +
                            "Content-Disposition: form-data; name=\"key\"\n" +
                            "\n" +
                            "myvalue1\n" +
                            "------WebKitFormBoundarycTqA2AimXQHBAJbZ";

            final List<Part> parts = MockPart.parseAll(mockContent);
            assertNotNull(parts);

            return parts;
        }
    };
}

The following is the error message that I encountered:

14:53:04.918 [main] ERROR de.com.adsl.sightly.model.Comment - Error Message: null
java.lang.UnsupportedOperationException: null
    at org.apache.sling.servlethelpers.MockSlingHttpServletRequest.getParts(MockSlingHttpServletRequest.java:882) ~[org.apache.sling.servlet-helpers-1.1.10.jar:?]
    at de.com.adsl.sightly.model.Comment.uploadFile(Feedback.java:137) ~[classes/:?]
    at de.com.adsl.sightly.model.Comment.setup(Feedback.java:82) [classes/:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_201]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_201]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_201]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_201]
    at org.apache.sling.models.impl.ModelAdapterFactory.invokePostConstruct(ModelAdapterFactory.java:792) [org.apache.sling.models.impl-1.3.8.jar:?]
    at org.apache.sling.models.impl.ModelAdapterFactory.createObject(ModelAdapterFactory.java:607) [org.apache.sling.models.impl-1.3.8.jar:?]
    at org.apache.sling.models.impl.ModelAdapterFactory.internalCreateModel(ModelAdapterFactory.java:335) [org.apache.sling.models.impl-1.3.8.jar:?]
    at org.apache.sling.models.impl.ModelAdapterFactory.getAdapter(ModelAdapterFactory.java:211) [org.apache.sling.models.impl-1.3.8.jar:?]
...

I have looked up various solutions online such as writing two mockito when statements but has not been successful. I would greatly appreciate any form of help or sharing of knowledge if you have encountered the following issue previously. Thank you!

From the source code of MockSlingServletResquest it always throws that exception as it's not supported yet by the mocked class.

https://github.com/apache/sling-org-apache-sling-servlet-helpers/blob/71ef769e5564cf78e49d6679a3270ba8706ae406/src/main/java/org/apache/sling/servlethelpers/MockSlingHttpServletRequest.java#L953

Maybe you should consider writing a servlet, or another approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM