I am trying to test my servlet for login page but the Mock test is throwing an exception
LoginServlet
/**
* #see HttpServlet#HttpServlet()
*/
public LoginServlet() {
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
HttpSession session = request.getSession(true);
boolean result = false;
String username = request.getParameter("username");
String password = request.getParameter("password");
result = obj.validateLogin(username, password);
if (result) {
session.setAttribute("username", username);
response.sendRedirect("UserHome.jsp");
} else {
response.sendRedirect("login.jsp");
}
return;
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
MockTest : this is the test case I have written for login
public class LoginServletMockTest {
#Test
public void testServlet() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
HttpSession session = request.getSession(true);
when(request.getParameter("username")).thenReturn("garwitauday");
when(request.getParameter("password")).thenReturn("123");
when(request.getSession()).thenReturn(session);
doNothing().when(session).setAttribute("username", "garwitauday");
doNothing().when(response).sendRedirect("Userhome.jsp");
LoginServlet loginservlet = new LoginServlet();
loginservlet.doPost(request, response);
verify(session).setAttribute("username", "garwitauday");
verify(response).sendRedirect("Userhome.jsp");
}
}
I am not able to resolve this issue
Create the mockito object for HttpSession also and set the mockito session object in request.
And continue your same do(..).when(..) or when(..).thenReturn(..) to mock the calls.
Make sure to set the attributes and parameters in request and session objects for easy testing.
If your's is mvc based servet, better to use MockMvc and it's builder objects.
Related
I have this doPost method:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html");
try {
HttpSession session = request.getSession();
synchronized (session) {
Class.forName("org.postgresql.Driver");
DataSource storage = DataSource.getInstance();
if (session.getAttribute("role").toString().equals("admin")) {
storage.update(request.getParameter("name"), request.getParameter("email"), request.getParameter("createDate"), request.getParameter("login"), request.getParameter("password"), request.getParameter("role"));
} else if(session.getAttribute("role").toString().equals("user")) {
storage.updateByUser(request.getParameter("name"), request.getParameter("email"), request.getParameter("createDate"), session.getAttribute("login").toString());
}
response.sendRedirect(String.format("%s/editUser", request.getContextPath()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
And i have this test:
#Test
public void editUser() throws SQLException {
ServletEditUser servlet = new ServletEditUser();
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
DataSource.getInstance().add("test", "test", "test", "test", "test", "admin");
when(request.getParameter("role")).thenReturn("admin");
when(request.getParameter("login")).thenReturn("test");
when(request.getParameter("name")).thenReturn("edit");
when(request.getParameter("createDate")).thenReturn("edit");
when(request.getParameter("password")).thenReturn("edit");
servlet.doPost(request, response);
List<User> users = DataSource.getInstance().getList();
assertThat(DataSource.getInstance().getList().get(users.size() - 1).getName(), is("edit"));
}
I'm don't understand, how I should test my doPost method. How I should setAttribute for session on JUnit test?
ANSWER:
In JUnit test, need to add:
HttpSession session = mock(HttpSession.class);
when(request.getSession()).thenReturn(session);
when(request.getSession().getAttribute("role")).thenReturn("admin");
In JUnit test, need to add:
HttpSession session = mock(HttpSession.class);
when(request.getSession()).thenReturn(session);
when(request.getSession().getAttribute("role")).thenReturn("admin");
I am getting HTTP Status 404 - /ShowForm this error pls help me to solve this.
ShowForm.html
<form action = "/ShowForm" method = "post" enctype="multipart/form-data" >
Name: <input type = "text" name = "name" /><br>
File: <input type = "file" name = "file" /><br>
<input type = "submit" value = "submit" name = "submit">
</form>
ShowForm.java
#WebServlet("/ShowForm")
public class ShowForm extends HttpServlet {
private static final long serialVersionUID = 1L;
public ShowForm() {
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());
response.setContentType("text/plain");
PrintWriter pw = response.getWriter();
ServletInputStream sis = request.getInputStream();
for(int i = sis.read();i != -1;i = sis.read())
{
pw.print((char)i);
}
}
/**
* #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);
}
}
Here I am using Annotation so I have not map in web.xml.
I try to insert some information in the table, but get such an error (NullPointerException). Maybe it causes of empty request, but I'm not sure.
Here is a log with error:
enter image description here
First Servlet:
#WebServlet("/clientServlet")
public class clientServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Client client = new Client();
client.setName(request.getParameter("name"));
client.setSurname(request.getParameter("surname"));
HttpSession session = request.getSession();
session.setAttribute(sessionKey.client, client);
response.sendRedirect("addTour.html");
}
The second one:
#WebServlet("/tourServlet")
public class tourServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Tour tour = new Tour();
tour.setCountryTo(request.getParameter("countryTo"));
tour.setAmountOfDays(request.getParameter("amountOfDays"));
session.setAttribute(sessionKey.tour, tour);
response.sendRedirect("final.jsp");
}
Problem appears in this Servlet:
#WebServlet("/dbServlet")
public class dbServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public dbServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
IRepositoryCatalog catalog = new RepositoryCatalog("jdbc:hsqldb:hsql://localhost/workdb");
HttpSession session = request.getSession();
Client client = (Client) session.getAttribute(sessionKey.client);
Tour tour = (Tour) session.getAttribute(sessionKey.tour);
catalog.Clients().add(client);
catalog.saveAndClose();
catalog.Tours().add(tour);
catalog.saveAndClose();
catalog.saveAndClose();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException a) {
a.printStackTrace();
}
}
At first impression i can say that maybe the first and second servlet are for a POST method so doing a doGet and trying to 'getParameter' you will get empty object and so throw a NullPointerException. Can you post something about your view?
(I would comment but i can't yet)
I have call this method under doGet. Please help me to get out of this.
This is my own method and I wanted to call this.
public void doYourThingHere(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String[] checkedQues = request.getParameterValues("ttom");
List<String> checkedQuesList = Arrays.asList(checkedQues);
Map<String, String> preferences = new LinkedHashMap<String, String>();
if (session.getAttribute("username") != null) {
List<Question> questionsList = (List<Question>) session
.getAttribute("restaurantQuestionList");
List<Question> questionsListTemp1 = new ArrayList<>();
for (int i = 2; i < 4; i++) {
questionsListTemp1.add(questionsList.get(i));
}
session.setAttribute("tomtomRestaurantQuestionList1",
questionsListTemp1);
for (Question question : questionsList) {
String questionId = String.valueOf(question.getId());
if (checkedQuesList.contains(questionId)) {
String answerId = request.getParameter(questionId);
// PreferenceDAO.storePreferences(questionId, answerId,
// CATEGORY);
preferences.put(questionId, answerId);
System.out.println("queid : " + questionId + "answerid : "
+ answerId);
}
}
String username = (String) session.getAttribute("username");
PreferencesProcessor.process(preferences, username);
RequestDispatcher requestdp = request
.getRequestDispatcher("WEB-INF/jsp/table.jsp");
requestdp.forward(request, response);
} else {
RequestDispatcher requestdp = request
.getRequestDispatcher("WEB-INF/jsp/login.jsp");
requestdp.forward(request, response);
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
/**
* #see HttpServlet doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
Servlets map HTTP request headers to predefined methods, such as doGet(), doPost(), and some others.
https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServlet.html
Since your method modifies data, you should call it with POST.
Most simple way is to forward your doPost() to this method:
public void doPost(HttpServletRequest request, HttpServletResponse response) {
doYourThingHere(request, response);
}
What will happen usually is that you'll add some routing logic to your doPost like that:
public void doPost(...) {
String action = request.getParameter("action");
switch (action) {
case "doSomething":
doSomething(request, response);
break;
case "somethingElse":
doSomethingElse(request, response);
break;
...
}
}
I am using a filter to determine whether or not a requested page has a valid session or not.
This is my code. web.xml:
<filter>
<filter-name>SessionFilter</filter-name>
<filter-class>
com.imagemanagementutility.filter.SessionFilter
</filter-class>
<init-param>
<param-name>avoid-urls</param-name>
<param-value>index.jsp</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Filter class:
public class SessionFilter implements Filter {
private ArrayList<String> urlList;
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String url = request.getServletPath();
boolean allowedRequest = false;
System.out.println(url.replace("/",""));
if (urlList.contains(url)) {
allowedRequest = true;
}
if (!allowedRequest) {
HttpSession session = request.getSession(false);
if (null == session) {
System.out.println("redirect in servlet session filter");
RequestDispatcher dispatcher = request
.getRequestDispatcher("//index.jsp");
dispatcher.forward(request, response);
}
}
chain.doFilter(req, res);
System.out.println("end");
}
public void init(FilterConfig config) throws ServletException {
String urls = config.getInitParameter("avoid-urls");
StringTokenizer token = new StringTokenizer(urls, ",");
urlList = new ArrayList<String>();
while (token.hasMoreTokens()) {
urlList.add(token.nextToken());
}
}
}
I have a login page which is used to check whether or not the user is valid.
If the user is valid then control is transfer to this servlet.
public class MainService extends HttpServlet {
private static final long serialVersionUID = 1L;
static Logger log = Logger.getLogger(MainService.class.getName());
/**
* #see HttpServlet#HttpServlet()
*/
public MainService() {
super();
}
/*
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
response.setContentType("text/html;charset=UTF-8");
LogUtil.logInfo("i m here");
List<Images> imageList = null;
response.setContentType("text/html");
try {
UserDataService userDataService = new UserDataImpl();
String userId = null;
String username = null;
String password = null;
username = request.getParameter("user");
password = request.getParameter("password");
userId = userDataService.checkUser(username, password);
if (userId!=null) {
System.out.println(userId);
session.setAttribute("userId", userId);
imageList = userDataService.getImages(userId);
session.setAttribute("imageList", imageList);
/*response.sendRedirect("//showUserImages.jsp");*/
RequestDispatcher dispatcher = request
.getRequestDispatcher("//showUserImages.jsp");
dispatcher.forward(request, response);
} else {
/*response.sendRedirect("//index.jsp");*/
RequestDispatcher dispatcher = request
.getRequestDispatcher("//index.jsp");
dispatcher.forward(request, response);
}
} catch (ImageException e) {
e.getMessage();
e.printStackTrace();
}
}
}
This works without the filter, but with the filter shows an error
when I forward control to "//showuserImages.jsp".
Put the invocation of doFilter in an else block:
if (!allowedRequest) {
HttpSession session = request.getSession(false);
if (null == session) {
System.out.println("redirect in servlet session filter");
RequestDispatcher dispatcher = request
.getRequestDispatcher("//index.jsp");
dispatcher.forward(request, response);
}
}else{
chain.doFilter(req, res);
}