Junit Test of servlet with eclipse - java

I'm not familiar with Junit testing. For example, how can I write a Unit test for this servlet?
I really don't know where to start, please!!!
Obviously he accesses the database and I don't know how to do the test to check if the credentials entered are present in the db. Could you give me an example about this servlet please?
/**
* Servlet implementation class LoginPatient
*/
#WebServlet("/LoginPatient")
public class LoginPatient extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public LoginPatient() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fiscal_code=request.getParameter("fiscal_code");
String user_password= request.getParameter("user_password");
PrintWriter out=response.getWriter();
ProfileManager pM=new ProfileManager();
UserBean patient= pM.ReturnPatientByKey(fiscal_code, user_password);
if(patient != null) {
HttpSession session= request.getSession();
session.setAttribute( "user" , patient);
session.setMaxInactiveInterval(-1);
out.println("1");
}
else {
out.println("0");
}
}
}

A unit test for this servlet should not actually access the DB. It should test that the servlet behaves correctly given the various results ProfileManager may return.
You need to use dependency injection so that you can mock ProfileManager in your unit test.
How you do this depends on your framework. In spring you would say:
#Component
public class LoginPatient extends HttpServlet {
...
#Autowired
public LoginPatient(ProfileManager profileManager) { ... }
...
}
Then in your test use Mockito (this is a sketch not compilable code)
public void testPresent() {
// mock the request and response, and the session
HttpServletRequest req = mock(HttpServletRequest.class);
Session session = mock(HttpSession.class);
when(req.getSession()).thenReturn(session);
...
// you might want to mock the UserBean instance too
ProfileManager pm = mock(ProfileManager.class);
when(pm.ReturnPatientByKey("aCode", "aPassword")).thenReturn(new UserBean(...));
LoginPatient servlet = new LoginPatient(pm);
servlet.doPost(req, res);
// verify that the session had the right things done to it
}

Related

How to add a new endpoint to my servlet?

I want to add a new endpoint call say 'getAll', how can I add it ?
say I want a URL to target: www.localhost:8080/Alpha/getAll ?
Do I need to create any annotation ?
#WebServlet("/Alpha")
public class Alpha extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Alpha() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Yes, I'd declare a new servlet with an #WebServlet annotation.
#WebServlet("/Alpha")
public class Alpha extends HttpServlet {
private static final long serialVersionUID = 1L;
...
No, this would NOT necessarily be available from the URL http://localhost:8080/Alpha"'.
The first level is your Context root. This is determined by your Servlet container (here, Tomcat); not anywhere in your Java code, your web.xml, or any possible annotations.
If your ContextRoot happened to be "/", then yes: http://localhost:8080/Alpha would work. But ordinarily, your endpoint would instead be something like http://localhost:8080/mywebapp/Alpha.
Here are several examples for setting a context root in the Eclipse IDE. The specifics may vary from Tomcat, JBoss, WebSphere/Liberty, etc.
Eclipse – How to change web project context root

Return ModelAndView from Spring when handling exceptions

Dealing with exceptionhandling in spring project.
I had followed this approach to handle the exceptions.
Everything is going good, but I want to return a ModelAndView instead of writing a text/html using PrintWriter object.
Following is the approach I followed.
ExceptionHandler.java
package com.test.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
/**
* Servlet implementation class ExceptionHandler
*/
#WebServlet("/ExceptionHandler")
public class ExceptionHandler extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
//processError(request,response);
handleException(request,response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//processError(request,response);
handleException(request,response);
}
//I want this ModelAndView to be returned and should display the page that was set in ModelANdView object.
private ModelAndView handleException(HttpServletRequest request,HttpServletResponse response) throws IOException {
ModelAndView model = new ModelAndView("ErrorPage");
model.addObject("errMsg", "this is Exception.class");
return model;
}
//I don't want this approach.
/*private void processError(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// Analyze the servlet exception
Throwable throwable = (Throwable) request
.getAttribute("javax.servlet.error.exception");
Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
String servletName = (String) request
.getAttribute("javax.servlet.error.servlet_name");
if (servletName == null) {
servletName = "Unknown";
}
String requestUri = (String) request
.getAttribute("javax.servlet.error.request_uri");
if (requestUri == null) {
requestUri = "Unknown";
}
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head><title>Exception/Error Details</title></head> <body>");
if(statusCode != 500){
out.write("<h3>Error Details</h3>");
out.write("<strong>Status Code</strong>:"+statusCode+"<br>");
out.write("<strong>Requested URI</strong>:"+requestUri);
}else{
out.write("<h3>Exception Details</h3>");
out.write("<ul><li>Servlet Name:"+servletName+"</li>");
out.write("<li>Exception Name:"+throwable.getClass().getName()+"</li>");
out.write("<li>Requested URI:"+requestUri+"</li>");
out.write("<li>Exception Message:"+throwable.getMessage()+"</li>");
out.write("</ul>");
}
out.write("<br><br>");
out.write("Home Page");
out.write("</body></html>");
}*/
}
And in web.xml I had added following tag to set location for error.
<error-page>
<error-code>404</error-code>
<location>/ExceptionHandler</location>
</error-page>
EDIT: I know that void cannot return ModelAndView Object , but looking for an approach to load the ErrorPage in case of invalid URL

Servlet doGet Method getting called multiple times for the same HTTP request

I have run into a weird problem. My servlet's doGet method is getting called multiple times for a single HTTP request. The rerun happens every 10-12 seconds till the initial process completes.
Below is my servlet code
private static final long serialVersionUID = WebServiceServlet.class.getCanonicalName().hashCode();
private ServletContext servletContext;
/**
* #see HttpServlet#HttpServlet()
*/
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
servletContext = servletConfig.getServletContext();
}
/*public WebServiceServlet() {
super();
}*/
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String output = null;
/*
* Calling the Operation Manager which will decide the operation type
* and call the corresponding operation binder and set the return
* response generated in http response.
*/
// Request Processing
response.setContentType("application/json; charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(output);
out.close();
}
#Override
public void destroy() {
super.destroy();
}
Below is the mapping in the web.xml
<servlet>
<description></description>
<display-name>WebServiceServlet</display-name>
<servlet-name>WebServiceServlet</servlet-name>
<servlet-class>com.servlet.WebServiceServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WebServiceServlet</servlet-name>
<url-pattern>/web.do</url-pattern>
</servlet-mapping>
I am using SEAM and JSF but this is a standalone servlet. There is no exception in the logs. I have also verified that the INIT method is being called only once. It is the service method which is being repeated. The identity hash code comes same for all the reruns (System.identityHashCode(this)).
The call is being made from a REST API tester. There are no multiple calls happening from the caller. The reruns are happening over the tomcat container.
I am at my wit's end. Has anyone else faced this issue?
I had faced the same issue.
Just keep the #post method in your servlet class. Comment out #get and #put if you have.
Thanks

How do I get and pass the JSESSIONID into another method

To begin I am a bit new to java.
I have a web application I have been assigned to work on. It collects various user inputs via form and sends them via an a4j commandButton to a method in my jar folder. The method uses the form data to construct a web service client call. Part of the requirement is that I pass, as an element in the web service call, the current JSESSIONID from the request.
Steps I have taken:
In the class that contains the method I am calling I have set up getters and setters (outside of the helper class below).
I have added a helper class to my class as follows:
class GetSessionId extends HttpServlet {
private String sessionid;
public void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
sessionid = session.getId();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public String getSessionId(){
return sessionid;
}
public void setSessionId(String sessionid){
this.sessionid=sessionid;
}
}
When I need the get the sessionid I used:
GetSessionId session_ID = new GetSessionId();
String sessionid = session_ID.getSessionId();
String sessionId = sessionid;
System.out.println("show me = " + sessionId);
But in the console (testing on my localhost) sessionid is null.
What am I doing wrong?

How do i get a HttpServletResponse object in Openxava

Currently I am working on Openxava frame work and it's new for me. I want to built a File download functionality in my current project, so for that i need a HttpServletResponse object. so please help me how do i get HttpServletResponse object in Openxava.
You can create a servlet and register it in servlets.xml (OpenXava adds the content of this file to web.xml upon deployment).
To enable the servlet for the user then create an action that implements IForwardAction.
For example servlet.xml might have:
<servlet>
<servlet-name>myDownloadServlet</servlet-name>
<servlet-class>org.webapp.test.MyDownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myDownloadServlet</servlet-name>
<url-pattern>/mydownload.do</url-pattern>
</servlet-mapping>
And the MyDownloadServlet class.
public class MyDownloadServlet extends HttpServlet {
/**
* Shows Hello World.
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().write("Hello World");
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Finally your action
public class MyDownloadAction extends ViewBaseAction implements IForwardAction {
public String getForwardAction() {
return "/mydownload.do";
}
public boolean inNewWindow() {
return true;
}
}
Federico

Categories

Resources