app/conf/routes
GET /api controllers.ApiController.api(x: Int, y: Int ?= 10)
app/services/Adder.scala
package services
import javax.inject.Singleton
trait Adder {
def add(x: Int, y: Int): Int
}
@Singleton
class ServiceAdder extends Adder {
override def add(x: Int, y: Int): Int = x + y
}
app/controllers/ApiController.scala
package controllers
import play.api.mvc._
import services.Adder
import javax.inject._
import scala.concurrent.ExecutionContext
@Singleton
class ApiController @Inject() (cc: ControllerComponents, adder: Adder)(
implicit ec: ExecutionContext
) extends AbstractController(cc) {
def api(x: Int, y: Int): Action[AnyContent] = Action { request =>
val r = adder.add(x, y)
Ok(s"$r")
}
}
app/Module.scala
import com.google.inject.AbstractModule
import services._
class Module extends AbstractModule {
override def configure() = {
bind(classOf[Adder]).to(classOf[ServiceAdder])
}
}
test/AdderTest.scala
package services
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.inject.{Binding, bind}
import play.api.mvc.Result
import play.api.test.FakeRequest
import play.api.test.Helpers._
import scala.concurrent.Future
class TestAdder extends Adder {
override def add(x: Int, y: Int): Int = 100 + x + y
}
class AdderTest extends PlaySpec with GuiceOneAppPerSuite {
val overrideModules: Seq[Binding[Adder]] = Seq(
bind[Adder].to[TestAdder]
)
override def fakeApplication(): Application =
new GuiceApplicationBuilder().overrides(overrideModules).build()
// ServiceAdder 테스트
"ServiceAdder" must {
"should be simple add" in {
val adder = new ServiceAdder()
adder.add(2, 4) mustBe 6
}
}
// fackApplication 에서 설정한대로 TestAdder 로 application 을 만들어
// route 테스트를 한다.
"ApiController" should {
"TestAdder should plus 100" in {
val futureRes: Future[Result] = route(app, FakeRequest(GET, "/api?x=2&y=4")).get
contentAsString(futureRes) mustBe "106"
}
}
}