我有这个 Web 服务 http://qa-takehome-creyzna.dev.aetion.com:4440
我想测试一下。我有身份验证详细信息(用户名和密码)并且该服务具有以下端点:/login、/user/、/user/{id} 和/user/search
。对于除/login 之外的所有端点,需要将授权 token 作为 HTTP header 传递。
该服务公开了一个登录端点 (/login),它接受一个带有两个参数的 POST 请求:用户名和密码。成功登录后,将返回一个身份验证 token ,必须使用该 token 向服务发出其他请求。例如,如果请求如下,
{
"username": "admin",
"password": "admin"
}
它可能会返回 { "token": "1234-0009-999"}
并且需要此 token 才能发出其他请求。
我需要验证 Web 服务,创建 10 个用户,然后检索该信息以验证用户是否已正确创建。我想制定一个测试计划并在 Eclipse 中实现。我该如何开始?
Web 服务基本上是 Java Servlet 的扩展,其中对输入进行更多处理,输出很少是 HTML 页面。
Netbeans 有一个关于如何建立 Web 服务的优秀教程,如果您遵循它,您可以在一小时内运行一个基本的 Web 服务。
https://netbeans.org/features/java-on-server/web-services.html
不要以为您必须使用一个 IDE(我喜欢 netbeans,但其他人不喜欢)或另一个而被愚弄。花哨的 GUI 工具只是编写普通的 Java 类,这些类可能会使用其他普通的 Java 工具(如使用 XML 的 JAXB 等)。
Web 服务只不过是一个 Web 服务器,它接受特定类型的请求,并以特定类型的响应进行响应。在 Java 中,Web 服务器通过利用 Servlet 变得更易于使用。 Servlet 的内部内容如下所示
Unpack the request
Validate the request is complete, report an error response if not
Act on the reqeust
Generate a response in the appropriate format
Send the response back as the reply.
--- 应要求编辑---
抱歉,这对我来说太明显了。让我填补空白。很抱歉掩盖了细节。
public class MockHttpServletRequest implements HttpServletRequest {
@Override
public String getAuthType() {
throw new UnsupportedOpertationException("unexpected method use");
}
@Override
public String getContextPath() {
throw new UnsupportedOpertationException("unexpected method use");
}
... repeat for all methods ....
}
public class ItemRequestWithBadEncoding extends MockHttpServletRequest {
@Override
public String getMethod() {
return "GET";
}
@Override
public String getHeader(String name) {
if ("content-type".equals(name)) {
return "text/plain-ish"; // this is not a mime-type
}
throw new IllegalArgumentException(String.format("this mock doesn't support %s", name);
}
... fill out the rest of the required request details ...
}
public class CapturingServletResponse implements HttpServletRespose {
private final ArrayList<Cookie> cookies = new ArrayList<Cookie>();
@Override
public void addCookie(Cookie cookie) {
cookies.add(cookie);
}
public List<Cookie> getCookies() {
return Collections.unmodifiableList(cookies);
}
... override other methods and capture them into per-instance fields
with ability to return unmodifiable references or copies to them ...
}
现在回到测试框架
@Test
public void testItemFetch() {
try {
MockRequest request= ItemRequestWithBadEncoding();
CapturingServletResponse response = new CapturingServletResponse();
Servlet itemRequestServlet = new ItemRequestServlet();
itemRequestServlet.service(request, response);
Assert.assertEquals("unexpected cookies in response", 0, response.getCookies().size());
... other asssertations ....
} catch (Exception e) {
Assert.assertFail(String.format("unexpected exception: %s", e.getMessage());
}
}
根据您关心的项目以及需要投入的工作量,您可以充实捕获所需的部分,并可能参数化和改进构建输入处理的方式。