Expand my Community achievements bar.

SOLVED

Issue in writing Unit Test using JUnit5 for Servlet

Avatar

Level 1

Hi,

So I am trying to write a JUnit unit test for a servlet. I set the RequestPathInfo using the following:

MockRequestPathInfo requestPathInfo = (MockRequestPathInfo) request.getRequestPathInfo();
requestPathInfo.setExtension("json");
requestPathInfo.setSuffix(null);
 
In the servlet, logic is written to split the requestPathInfo at "," using the following line of code:
 String pathInfo= String.valueOf(request.getRequestPathInfo());
 String[] spath = pathInfo.split(",");
 
When running the test, the pathInfo variable does not hold the content of RequestPathInfo. Instead, it has the mock object as string, like, org.apache.sling.testing.mock.sling.servlet.MockRequestPathInfo@4def7d36
This is stopping the further execution from happening in the unit test resulting in test failure. 
Could anyone please suggest a way through which I can get the content of RequestPathInfo instead of the mock object string while running the test. 
Note: It works perfectly on server though.
 
Thanks in advance!


1 Accepted Solution

Avatar

Correct answer by
Employee Advisor

Hi @shivani_panchal39 ,

 

In your code you are converting the RequestPathInfo object to a string, that's why you are seeing that behavior here

 String pathInfo= String.valueOf(request.getRequestPathInfo());

 

Not sure what would you want to read from requestParhInfo, but you could use 

requestPathInfo.setExtension("json");
requestPathInfo.setSuffix("temp");
requestPathInfo.setSelectorString("str1");

and in the Servlet, read the values from the reqPathInfo object

request.getRequestPathInfo().getExtension()
request.getRequestPathInfo().getSelectorString()

 

Regards,

Nitesh

View solution in original post

1 Reply

Avatar

Correct answer by
Employee Advisor

Hi @shivani_panchal39 ,

 

In your code you are converting the RequestPathInfo object to a string, that's why you are seeing that behavior here

 String pathInfo= String.valueOf(request.getRequestPathInfo());

 

Not sure what would you want to read from requestParhInfo, but you could use 

requestPathInfo.setExtension("json");
requestPathInfo.setSuffix("temp");
requestPathInfo.setSelectorString("str1");

and in the Servlet, read the values from the reqPathInfo object

request.getRequestPathInfo().getExtension()
request.getRequestPathInfo().getSelectorString()

 

Regards,

Nitesh