sat*_*shi 5 dependency-injection scala playframework-2.0
我是Play框架和scala的新手,我正试图在一个伴侣对象中注入一个依赖项.
我有一个简单的案例类,如:
case class Bar(foo: Int) {}
Run Code Online (Sandbox Code Playgroud)
使用伴侣对象:
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))
}
Run Code Online (Sandbox Code Playgroud)
这很好,但它并不是一个干净的方式.我希望能够在构建时注入依赖项,这样我可以在测试时注入不同的模拟对象,并在开发和生产中注入不同的实际实现.
实现这一目标的最佳方法是什么?
任何帮助真的很感激.谢谢!
沿着Cake的思路,我们可以尝试将您的示例更改为
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
Run Code Online (Sandbox Code Playgroud)
您还应该尝试测试此示例是否也适合 Play 框架
| 归档时间: |
|
| 查看次数: |
1354 次 |
| 最近记录: |