我有一些具有混合特征的组件,其中包含系统逻辑(缓存,服务等)。并且需要在测试中模拟这个逻辑。这很简单......
但我还需要测试具有相同缓存的组件包,并且我无法共享一些全局缓存。所以,我的解决方案是:
在代码中:
trait Component
class MyComponent1 extends Component with Cache with Services { ... }
class MyComponent2 extends Component with Cache with Services { ... }
trait Cache {
private val _cache = ...
def query(...) = ...
}
在测试API中:
trait CacheMock extends Cache {
private[package] var _cache = null //to be injected
override def query(...) = _cache.get(...)
}
case class Config(cacheMock: Cache)
trait TestAPI {
val componentCreator: => List[Component]
def test(config: Config) = {
val instances = componentCreator
instances foreach {
case mocked: CacheMock => mocked._cache = config.cacheMock
case _ =>
}
instances
}
}
在测试中:
class Test extends TestAPI {
def componentCreator = List(new MyComponent1 with CacheMock, new MyComponent2 with CacheMock)
test(Config(mock1))
test(Config(mock2))
}
另一种解决方案是在componentCreator中使用参数化工厂:Cache =>列出[组件],但它有点难看。
那么有没有更好的解决方案,它还可以提供简单的DSL(没有样板),但没有var分配?或者可以解决相同问题的框架?
答案 0 :(得分:0)
不像你的代码那样编译,但它应该解释我的想法:
class TestMyComponent1(protected _cache: Cache) extends MyComponent1 with CacheMock
class TestMyComponent2(protected _cache: Cache) extends MyComponent2 with CacheMock
trait CacheMock extends Cache {
protected val _cache: Cache
override def query(...) = _cache.get(...)
}
class Test extends TestAPI {
def componentCreator = List(new TestMyComponent1(mock1), new TestMyComponent2(mock2))
}