我正在尝试为我的程序编写单元测试并使用模拟数据。我对如何拦截对 URL 的 HTTP Get 请求有点困惑。
我的程序调用 API 的 URL,并返回一个简单的 XML 文件。我希望测试不是从在线 API 获取 XML 文件,而是从我这里接收预定的 XML 文件,以便我可以将输出与预期输出进行比较,并确定一切是否正常工作。
有人向我指出了 Mockito,并且看到了许多不同的示例,例如这篇 SO 帖子,如何使用 Mockito 来测试 REST 服务?但我并不清楚如何设置这一切以及如何模拟数据(即,每当调用 URL 时都返回我自己的 xml 文件)。
我唯一能想到的是制作另一个在 Tomcat 上本地运行的程序,并在我的测试中传递一个特殊的 URL,该 URL 调用 Tomcat 上本地运行的程序,然后返回我想要测试的 xml 文件。但这似乎有点矫枉过正,我认为这是不可接受的。有人可以指出我正确的方向吗?
private static InputStream getContent(String uri) {
HttpURLConnection connection = null;
try {
URL url = new URL(uri);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
return connection.getInputStream();
} catch (MalformedURLException e) {
LOGGER.error("internal error", e);
} catch (IOException e) …Run Code Online (Sandbox Code Playgroud) 嵌入在JDK 6中的Http Server是开发Web服务的一个很大的帮助,但是我遇到了我发布了一个Endpoint然后代码崩溃并让服务器运行的情况.
一旦丢失对它的引用(或已发布的端点),如何关闭嵌入式服务器?
我知道J2EE可以用于JSP + Servlets.但是,我可以将J2SE用于JSP和Servlets吗?
我是 Java 新手。我在 中使用了写入服务器Golang。我需要将回复发送至HttpExchange. 这是我的代码:
public static void main(String[] args) throws IOException
{
Server = HttpServer.create(new InetSocketAddress(8000),0);
Server.createContext("/login", new SimpleHandler());
Server.setExecutor(null);
Server.start();
}
class SimpleHandler implements HttpHandler
{
@Override
public void handle(HttpExchange request) throws IOException
{
//Here I need to do like request.Response.Write(200,"DONE");
}
}
Run Code Online (Sandbox Code Playgroud) 我需要传达我的Java应用程序和网站。由于某种原因,我选择使用HttpServer类。(我真的不懂PHP)。我看了这个问题:仅使用Java SE API的Java中的简单HTTP服务器
这是我使用的HttpHandler代码:
public class NexusHttpHandler implements HttpHandler{
private String response;
public NexusHttpHandler(String response){
this.response=response;
}
@Override
public void handle(HttpExchange he) throws IOException {
System.out.println("I am called!");
System.out.println(he.getRequestHeaders().keySet());
System.out.println(he.getRequestHeaders().values());
he.sendResponseHeaders(200, response.length());
OutputStream os = he.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
Run Code Online (Sandbox Code Playgroud)
由于某种原因,每次刷新页面都会两次调用“我被叫”。这是完整的输出:
I am called!
[Cache-control, Host, Accept-encoding, Connection, Accept-language, User-agent, Accept]
[[max-age=0], [localhost:8080], [gzip,deflate,sdch], [keep-alive], [ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4], [Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36], [text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8]]
I am called!
[Host, Accept-encoding, Connection, Accept-language, User-agent, Accept]
[[localhost:8080], [gzip,deflate,sdch], …Run Code Online (Sandbox Code Playgroud) java ×5
http ×2
httpserver ×1
jakarta-ee ×1
java-ee ×1
jdk1.6 ×1
junit ×1
mockito ×1
sockets ×1
unit-testing ×1
web ×1