【发布时间】:2016-06-07 20:40:57
【问题描述】:
我正在尝试开发一个简单的单元测试来绑定我机器上的端口,测试端口是否已绑定,然后释放端口并测试它是否已释放。目前我正在使用这种幼稚的方法
class ServerTest extends FlatSpec with MustMatchers {
"Server" must "bind a tcp server to an address on our machine" in {
//if this fails this means that the port is in use before our test case is run
val port = 18333
isBound(port) must be (false)
val actor = Server()
actor ! Tcp.Bind(actor, new InetSocketAddress(port))
Thread.sleep(1000)
isBound(port) must be (true)
Thread.sleep(1000)
actor ! Tcp.Unbind
Thread.sleep(1000)
isBound(port) must be (false)
}
/**
* Tests if a specific port number is bound on our machine
* @param port
* @return
*/
def isBound(port : Int) : Boolean = {
val tryBinding : Try[Unit] = Try {
val socket = new java.net.Socket()
socket.connect(new java.net.InetSocketAddress(port),1000)
socket.close()
}
tryBinding.isSuccess
}
}
我想在不调用Thread.sleep 的情况下对此进行测试,因为这是一个阻塞调用。谁能给我一个更惯用的解决方案?
【问题讨论】:
标签: multithreading scala akka