【问题标题】:Testing akka tells without using Thread.sleep在不使用 Thread.sleep 的情况下测试 akka
【发布时间】: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


    【解决方案1】:

    发送 TCP.Bind 时,您应该会收到说明成功或失败的回复:http://doc.akka.io/japi/akka/2.3.2/akka/io/Tcp.Bind.html

    Bind消息发送给TCP manager actor,得到 通过 TcpExt.manager() 绑定到监听套接字。这 经理回复 Tcp.CommandFailed 或演员处理 侦听套接字以 Tcp.Bound 消息回复。如果本地端口 在 Bind 消息中设置为 0,那么 Tcp.Bound 消息应该是 检查以找到绑定到的实际端口。

    您应该使用 AkkaTestKit (http://doc.akka.io/docs/akka/snapshot/scala/testing.html) 并使用ImplicitSenderTestProbe 发送TCP.Bind,然后等待答复。

    例如:

    val probe = TestProbe()
    probe.send(actor, Tcp.Bind(actor, new InetSocketAddress(port)))
    probe.expectMsg(Tcp.Bound)
    

    您的测试代码将在收到回复后继续,如果在超时内未收到则失败(可在expectMsg 调用中配置)。

    【讨论】:

    【解决方案2】:

    你可以使用

    within (1000 millisends) {
    ...
    }
    

    更多示例请参见https://github.com/RayRoestenburg/AkkaExamples/blob/master/src/test/scala/unit/akka/TestKitUsageSpec.scala

    【讨论】:

    • 我熟悉within,但是我不熟悉如何使用within 来确定这些事件的顺序是否经过正确测试。
    猜你喜欢
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 2013-12-13
    • 1970-01-01
    相关资源
    最近更新 更多