我是 Play 框架和 scala 的新手,我正在尝试在伴随对象中注入(inject)依赖项。
我有一个简单的案例类,例如:
case class Bar(foo: Int) {}
有一个伴随对象,如:
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))
}
这很好用,但这并不是一种真正干净的方法。我希望能够在构建时注入(inject)依赖项,以便在测试时注入(inject)不同的模拟对象,并在开发和生产中注入(inject)不同的实际实现。
实现这一目标的最佳方法是什么?
任何帮助都非常感谢。谢谢!
最佳答案
沿着蛋糕的路线,我们可以尝试将您的示例更改为
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
您还应该尝试测试此示例是否也适合 Play 框架
关于scala - 在对象中注入(inject)依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15429080/