我正在编写一个客户端-服务器系统。我想写一个黄瓜测试来测试两者是否正确交互。
但是,如果我将服务器和客户端都放入一个测试中,当我的服务器开始接受连接时,它将阻塞并且测试不会继续。这是正常的,因为服务器在侦听连接时应该阻止。
那么我应该如何进行这样的测试呢?
我的黄瓜功能是这样的:
Feature: Client Can Connect.
Scenario: Client can connect to server.
Given Server is up and running.
When Client is up and tries to connect to server.
Then Server accepts connection.
我对此的步骤定义是:
public class ClientConnectsServerStepDefinition {
@Given("^server is up and running$")
public void server_is_up_and_running() {
TheServer theServer = new TheServer("localhost", 5776);
theServer.start(); //The whole test would block at here and would not proceed
}
@When("^client is up and tries to connect to server$")
public void client_is_up_and_tries_to_connect() {
TheClient theClient = new TheClient("localhost", 5776);
theClient.start();
}
@Then("^server accepts connection.$")
public void the_server_accepts_connection() {
Assert.assertTrue(theServer.isConnected);
}
}
我曾经尝试将服务器和客户端放在单独的线程中。但这无济于事,因为我无法从服务器或客户端获得任何反馈,因为它们分为两个线程。
我是否正确编写了测试?请批评我的代码。感谢任何强有力的手。
在单独的线程中启动服务器。使其成为守护进程线程,以便在客户端停止时停止一切,或者在(最后一个)客户端断开连接时退出。