Web 服务基本上是 Java Servlet 的扩展,其中输入被处理得更多,而输出很少是 HTML 页面。
Netbeans 有一个关于如何建立 Web 服务的优秀教程,如果你遵循它,你可以在一个小时内运行一个基本的 Web 服务。
https://netbeans.org/features/java-on-server/web-services.html
不要误以为您必须使用一个 IDE(我喜欢 netbeans,但其他人不喜欢)或另一个。花哨的 GUI 工具只是编写普通的 Java 类,这些类可能使用其他普通的 Java 工具(如 JAXB,如果使用 XML 等)。
Web 服务只不过是接受特定类型请求并以特定类型响应进行响应的 Web 服务器。在 Java 中,通过利用 Servlet,Web 服务器变得更容易使用。 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());
}
}
根据您关心的项目以及需要投入多少工作,您可以充实捕获所需的部分,或许还可以参数化和优化您构建输入处理的方式。