Introduce a dependency inside an object

I am new to the Play and scala platforms and I am trying to inject dependency inside a companion object.

I have a simple case class, for example:

case class Bar(foo: Int) {}

With a companion object like:

object Bar {
  val myDependency =
  if (isTest) {
    // Mock
  }
  else
  {
    // Actual implementation
  }

  val form = Form(mapping(
    "foo" -> number(0, 100).verifying(foo => myDependency.validate(foo)), 
  )(Bar.apply)(Bar.unapply))
}

This works great, but it is not a completely clean way to do this. I would like to be able to introduce dependencies during assembly, so that I can introduce various mock objects during testing and various real implementations during development and production.

What is the best way to achieve this?

Any help really appreciated. Thank!

+5
source share
1 answer

Along the Cake lines, we can try changing your example to

trait Validator {
    def validate(foo: Int): Boolean
}

trait TestValidation {
    val validator = new Validator {
        def validate(foo: Int): Boolean = ...   
    }
}

trait ImplValidation {
    val validator = new Validator {
        def validate(foo: Int): Boolean = ...   
    }
}


trait BarBehavior {
    def validator: Validator

    val form = Form(mapping(...))(Bar.apply)(Bar.unapply)
}

//use this in your tests
object TestBar extends BarBehavior with TestValidation

//use this in production
object ImplBar extends BarBehavior with ImplValidation

, , .

0

All Articles