这是我使用嵌入式 http 服务器提出的解决方案。在 OrderSteps.java 粘合代码中,我添加了一个用于在另一个线程上启动服务器的类。
private static class Callback implements Runnable
{
public void run()
{
HttpServer server;
try
{
server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/callback", new CallbackHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
catch (IOException e)
{
logger.debug("HTTP server loop failure.", e);
}
}
static class CallbackHandler implements HttpHandler
{
@Override
public void handle(HttpExchange t) throws IOException
{
// Read the message and set the global variable
// which informs the main test thread a callback
// has been received.
InputStream is=t.getRequestBody();
byte[] buf=new byte[1000];
int len=is.read(buf);
OrderSteps.receivedCallback=new String(buf,0,len);
String response = "Callback received.";
t.sendResponseHeaders(200, response.length());
// Send response
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
然后在 OrderSteps 类中,在发布订单的步骤/方法中,启动服务器线程,然后提交订单。这保证了服务器将收到回调,因为它在提交订单之前正在侦听。
// Start a listener for the callback.
Thread callbackThread = new Thread(new Callback());
callbackThread.start();
在检查是否收到回调的步骤/方法中,有一个循环检查静态变量以查看它是否已设置。
// Allow 5 seconds for the callback to occur.
for (int i = 0; i < 5; i++)
{
if (receivedCallback != null) {
break;
}
Thread.sleep(1000);
}
if (receivedCallback == null) fail("Callback was not received.");
assertEquals("Expected callback message", receivedCallback);