1

当我将服务部署到容器时,我正在使用 Cucumber 来测试我的服务。请求包含操作成功时服务调用的 URL。创建等待 Http 回调的 Cucumber 测试的好方法是什么?小黄瓜脚本看起来像。

Scenario: Process Order
    Given An Order has been submitted
    When the Order is processed
    Then the order process service calls back with a successful status message

Java 粘合代码会是什么样子?

4

1 回答 1

0

这是我使用嵌入式 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); 
于 2015-09-03T14:04:11.260 回答