ThriftMux Unit Test Roundtrip

I have decided to write this blog post mainly for my own reference. Today I was working on a Thrift service that I wanted to start and test within a unit test. All our services are using the Finagle RPC framework with ThriftMux as transport. I will show you how to find a free port on your machine to start the server on and then create a client to invoke that server. Given this Thrift IDL file.

namespace com.github.reikje
service MicroService {
string request()
}


using Scrooge or the scrooge-sbt-plugin, this is a ScalaTest that does exactly that.

package com.github.reikje
import java.net.{InetAddress, InetSocketAddress}
import com.twitter.finagle.{Address, Name, ThriftMux, param}
import com.twitter.util.{Await, Future}
import org.scalatest.{Matchers, WordSpec}
class RoundtripSpec extends WordSpec with Matchers {
"Microservice" should {
"respond to requests" in {
val service = new MicroServiceImpl("foo")
val server = ThriftMux.server
.configured(param.Label("zuul-thrift"))
.serveIface(new InetSocketAddress(InetAddress.getLoopbackAddress, 0), service)
val client = ThriftMux.client.newIface[MicroService.FutureIface](
Name.bound(Address(server.boundAddress.asInstanceOf[InetSocketAddress])), "microservice-client"
)
val response = Await.result(client.request())
response shouldBe "foo"
}
}
}
class MicroServiceImpl(response: String) extends MicroService.FutureIface {
override def request(): Future[String] = Future.value(response)
}