gpt4 book ai didi

java - 如何对 HTTPServlet 进行单元测试?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:12:57 26 4
gpt4 key购买 nike

我想用 http://www.easymock.org/ 测试我的 servlet

如何编写单元测试代码?

我根据您的回复更新我的代码。

我刚刚使用 Google 并制作了这段代码。

这是我的 Servlet:

 package com.i4ware.plugin.timesheet;

import java.io.IOException;

import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.IssueManager;
import com.atlassian.jira.project.Project;
import com.atlassian.jira.project.ProjectManager;
import org.ofbiz.core.entity.DelegatorInterface;
import org.ofbiz.core.entity.EntityExpr;
import org.ofbiz.core.entity.EntityOperator;
import org.ofbiz.core.entity.GenericEntityException;
import org.ofbiz.core.entity.GenericValue;
import org.ofbiz.core.util.UtilMisc;
import org.apache.commons.lang.StringEscapeUtils;
import com.atlassian.crowd.embedded.api.User;
import com.atlassian.jira.security.JiraAuthenticationContext;
import com.atlassian.jira.web.bean.PagerFilter;
import com.atlassian.jira.issue.search.SearchResults;
import com.atlassian.jira.bc.issue.search.SearchService;
import com.atlassian.jira.issue.search.SearchException;

import com.atlassian.jira.issue.worklog.Worklog;
import com.atlassian.jira.issue.worklog.WorklogManager;
import com.atlassian.jira.issue.worklog.WorklogImpl;

import com.atlassian.query.Query;
import com.atlassian.jira.jql.builder.JqlQueryBuilder;
import com.atlassian.query.order.SortOrder;

import com.atlassian.jira.issue.status.Status;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.atlassian.jira.util.json.JSONObject;
import com.atlassian.jira.util.json.JSONException;
import com.atlassian.jira.util.json.JSONArray;

import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Collections;
import java.lang.Long;
import java.util.Collection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.lang.Class;
import java.util.Enumeration;

import org.apache.log4j.Category;

import com.atlassian.upm.api.license.entity.PluginLicense;
import com.atlassian.upm.license.storage.lib.PluginLicenseStoragePluginUnresolvedException;
import com.atlassian.upm.license.storage.lib.ThirdPartyPluginLicenseStorageManager;

import com.atlassian.plugin.webresource.WebResourceManager;
import com.atlassian.templaterenderer.TemplateRenderer;

import java.text.ParseException;
import java.text.ParsePosition;

public class UserIsLogedInServlet extends HttpServlet
{
private static final Category log = Category.getInstance(UserIsLogedInServlet.class);
/** value is made for JSON {"success":true} or {"success":false}. */
private Boolean value;

private String json;
private String msg;
private final ThirdPartyPluginLicenseStorageManager licenseManager;
private WebResourceManager webResourceManager;
private final TemplateRenderer renderer;

private JiraAuthenticationContext authenticationContext;

public UserIsLogedInServlet(ThirdPartyPluginLicenseStorageManager licenseManager,
WebResourceManager webResourceManager,
TemplateRenderer renderer,
JiraAuthenticationContext authenticationContext)
{
this.licenseManager = licenseManager;
this.webResourceManager = webResourceManager;
this.renderer = renderer;
this.authenticationContext = authenticationContext;
}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
resp.setContentType("application/json");

}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{

User targetUser = authenticationContext.getLoggedInUser();

String user = "";

if (targetUser==null) {

user = "anonymous";
value = Boolean.valueOf(!"false"
.equalsIgnoreCase((String) "false"));
msg = "You're not loged in.";
} else {

user = targetUser.getName();
value = Boolean.valueOf(!"false"
.equalsIgnoreCase((String) "true"));
msg = "You're loged in.";
}

try {

json = new JSONObject()
.put("msg", msg)
.put("success", value)
.toString();

} catch (JSONException err) {
err.printStackTrace();
System.out.println("Got an JSONException: " + err.getCause());
}

resp.setContentType("application/json");
resp.getWriter().write(json);
resp.getWriter().close();

}
}

代码如下:

package com.i4ware.plugin.timesheet;

import junit.framework.*;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.BeforeClass;
import org.junit.After;
import java.io.*;
import java.security.*;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import javax.servlet.RequestDispatcher;
import static org.easymock.EasyMock.*;
import org.easymock.IMocksControl;
import com.atlassian.upm.api.license.entity.PluginLicense;
import com.atlassian.upm.license.storage.lib.PluginLicenseStoragePluginUnresolvedException;
import com.atlassian.upm.license.storage.lib.ThirdPartyPluginLicenseStorageManager;
import com.atlassian.plugin.webresource.WebResourceManager;
import com.atlassian.templaterenderer.TemplateRenderer;
import com.atlassian.jira.security.JiraAuthenticationContext;

import com.i4ware.plugin.timesheet.UserIsLogedInServlet;

public class UserIsLogedInServletTest extends TestCase {

private ThirdPartyPluginLicenseStorageManager licenseManager;
private WebResourceManager webResourceManager;
private TemplateRenderer renderer;
private JiraAuthenticationContext authenticationContext;

private IMocksControl mocks;
private UserIsLogedInServlet servlet;

@BeforeClass
public void setUpBeforeClass() {
mocks = (IMocksControl) createStrictControl();
servlet = new UserIsLogedInServlet(licenseManager,webResourceManager,renderer,authenticationContext);
}

@After
public void tearDown() {
mocks.reset();
}

@Test
public void testGet()throws ServletException, IOException {
HttpServletRequest request = mocks.createMock(HttpServletRequest.class);
HttpServletResponse response = mocks.createMock(HttpServletResponse.class);
expect(request.getRequestDispatcher("/plugins/servlet/timesheet/userislogedin")).andReturn(createMock(RequestDispatcher.class));
replay(request, response);
servlet.doGet(request, response);
verify(request, response);
}

@Test
public void testPost() throws ServletException, IOException {
HttpServletRequest request = mocks.createMock(HttpServletRequest.class);
HttpServletResponse response = mocks.createMock(HttpServletResponse.class);
expect(request.getRequestDispatcher("/plugins/servlet/timesheet/userislogedin")).andReturn(createMock(RequestDispatcher.class));
replay(request, response);
servlet.doPost(request, response);
verify(request, response);
}

}

我收到这个错误:

Tests run: 2, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: 0.046 sec <<< FAILURE!
testPost(com.i4ware.plugin.timesheet.UserIsLogedInServletTest) Time elapsed: 0.01 sec <<< ERROR!
java.lang.NullPointerException
at com.i4ware.plugin.timesheet.UserIsLogedInServletTest.testPost(UserIsLogedInServletTest.java:67)

testGet(com.i4ware.plugin.timesheet.UserIsLogedInServletTest) Time elapsed: 0 sec <<< ERROR!
java.lang.NullPointerException
at com.i4ware.plugin.timesheet.UserIsLogedInServletTest.testGet(UserIsLogedInServletTest.java:58)

最佳答案

您需要同时模拟 HttpServletRequestHttpServletResponse 对象。有existing implementations , easier to use与标准模拟相比。

一旦你有了请求和响应实例,你就遵循这个模式:

private final MyServlet servlet = new MyServlet();

@Test
public void testServlet() {
//given
MockHttpServletRequest req = //...
MockHttpServletResponse resp = //...

//when
servlet.service(req, resp);

//then
//verify response headers and body here
}

关于java - 如何对 HTTPServlet 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14404808/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com