Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Testing private/protected methods in ScalaTest:
- // This test is based on https://pastebin.com/eHqiDQWf
- // Let's test "resultFuture" method which is protected!
- "A MyController" when {
- ...
- "resultFuture is called" should {
- "return 5" in {
- controller.resultFuture.futureValue mustBe 5
- }
- }
- }
- // output:
- // [error] Access to protected method resultFuture not permitted because
- // [error] enclosing class TrixSpec is not a subclass of
- // [error] class MyController in package controllers where target is defined
- // [error] controller.resultFuture.futureValue mustBe 5
- // OK, let's mix-in PrivateMethodTester trait and replace "." with "invokePrivate":
- class TrixSpec extends ... with PrivateMethodTester {
- "A MyController" when {
- ...
- "resultFuture is called" should {
- "return 5" in {
- val resultFuture: PrivateMethod[Future[Int]] = PrivateMethod[Future[Int]]('resultFuture)
- controller.invokePrivate(resultFuture()).futureValue mustBe 5
- }
- }
- }
- }
- ' // output:
- // [info] TrixSpec:
- // [info] A MyController
- // [info] when resultFuture is called
- // [info] application - Future started
- // [info] application - Future finished
- // [info] - should return 5
- // [info] ScalaTest
- // [info] Run completed in 4 seconds, 592 milliseconds.
- // [info] Total number of tests run: 1
- // [info] Suites: completed 1, aborted 0
- // [info] Tests: succeeded 1, failed 0, canceled 0, ignored 0, pending 0
- // [info] All tests passed.
- // full code sample:
- import scala.concurrent.duration._
- import scala.concurrent.{ExecutionContext, Future}
- import scala.language.postfixOps
- import controllers.MyController
- import org.scalatest.PrivateMethodTester
- import org.scalatest.concurrent.ScalaFutures._
- import org.scalatest.mockito.MockitoSugar
- import org.scalatestplus.play.PlaySpec
- import play.api.mvc.ControllerComponents
- import play.api.test.Helpers
- class TrixSpec extends PlaySpec with MockitoSugar with PrivateMethodTester {
- private val cc: ControllerComponents = Helpers.stubControllerComponents()
- implicit val ec: ExecutionContext = cc.executionContext
- implicit val patienceConfig: PatienceConfig = PatienceConfig(timeout = 5 seconds, interval = 100 milliseconds)
- private val controller = new MyController(cc)
- "A MyController" when {
- "resultFuture is called" should {
- "return 5" in {
- val resultFuture: PrivateMethod[Future[Int]] = PrivateMethod[Future[Int]]('resultFuture)
- controller.invokePrivate(resultFuture()).futureValue mustBe 5
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement